events.lib.php 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449
  1. <?php
  2. /* See license terms in /license.txt */
  3. //use Chamilo\UserBundle\Entity\User;
  4. use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
  5. use ChamiloSession as Session;
  6. /**
  7. * Class Event
  8. * Functions of this library are used to record informations when some kind
  9. * of event occur. Each event has his own types of informations then each event
  10. * use its own function.
  11. */
  12. class Event
  13. {
  14. /**
  15. * @author Sebastien Piraux <piraux_seb@hotmail.com>
  16. * @desc Record information for open event (when homepage is opened)
  17. */
  18. public static function open()
  19. {
  20. global $_configuration;
  21. global $TABLETRACK_OPEN;
  22. // @getHostByAddr($_SERVER['REMOTE_ADDR']) : will provide host and country information
  23. // $_SERVER['HTTP_USER_AGENT'] : will provide browser and os information
  24. // $_SERVER['HTTP_REFERER'] : provide information about refering url
  25. if (isset($_SERVER['HTT_REFERER'])) {
  26. $referer = Database::escape_string($_SERVER['HTTP_REFERER']);
  27. } else {
  28. $referer = '';
  29. }
  30. // record informations only if user comes from another site
  31. //if(!eregi($_configuration['root_web'],$referer))
  32. $pos = strpos($referer, $_configuration['root_web']);
  33. if ($pos === false && $referer != '') {
  34. $ip = api_get_real_ip();
  35. $remhost = @gethostbyaddr($ip);
  36. if ($remhost == $ip) {
  37. $remhost = "Unknown";
  38. } // don't change this
  39. $reallyNow = api_get_utc_datetime();
  40. $params = [
  41. 'open_remote_host' => Database::escape_string($remhost),
  42. 'open_agent' => $_SERVER['HTTP_USER_AGENT'],
  43. 'open_referer' => $referer,
  44. 'open_date' => $reallyNow,
  45. ];
  46. Database::insert($TABLETRACK_OPEN, $params);
  47. }
  48. return 1;
  49. }
  50. /**
  51. * @author Sebastien Piraux <piraux_seb@hotmail.com> old code
  52. * @author Julio Montoya
  53. *
  54. * @param int $userId
  55. *
  56. * @return bool
  57. * @desc Record information for login event when an user identifies himself with username & password
  58. */
  59. public static function eventLogin($userId)
  60. {
  61. $userInfo = api_get_user_info($userId);
  62. $userId = (int) $userId;
  63. if (empty($userInfo)) {
  64. return false;
  65. }
  66. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  67. $reallyNow = api_get_utc_datetime();
  68. $userIp = Database::escape_string(api_get_real_ip());
  69. $sql = "INSERT INTO $table (login_user_id, user_ip, login_date, logout_date) VALUES
  70. ($userId,
  71. '$userIp',
  72. '$reallyNow',
  73. '$reallyNow'
  74. )";
  75. Database::query($sql);
  76. // Auto subscribe
  77. $user_status = $userInfo['status'] == SESSIONADMIN ? 'sessionadmin' : $userInfo['status'] == COURSEMANAGER ? 'teacher' : $userInfo['status'] == DRH ? 'DRH' : 'student';
  78. $autoSubscribe = api_get_setting($user_status.'_autosubscribe');
  79. if ($autoSubscribe) {
  80. $autoSubscribe = explode('|', $autoSubscribe);
  81. foreach ($autoSubscribe as $code) {
  82. if (CourseManager::course_exists($code)) {
  83. CourseManager::subscribeUser($userId, $code);
  84. }
  85. }
  86. }
  87. return true;
  88. }
  89. /**
  90. * @param int $sessionId
  91. *
  92. * @return bool
  93. */
  94. public static function isSessionLogNeedToBeSave($sessionId)
  95. {
  96. if (!empty($sessionId)) {
  97. $visibility = api_get_session_visibility($sessionId);
  98. if (!empty($visibility) && $visibility != SESSION_AVAILABLE) {
  99. $extraFieldValue = new ExtraFieldValue('session');
  100. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  101. $sessionId,
  102. 'disable_log_after_session_ends'
  103. );
  104. if (!empty($value) && isset($value['value']) && (int) $value['value'] == 1) {
  105. return false;
  106. }
  107. }
  108. }
  109. return true;
  110. }
  111. /**
  112. * @author Sebastien Piraux <piraux_seb@hotmail.com>
  113. * @desc Record information for access event for courses
  114. *
  115. * @return bool
  116. */
  117. public static function accessCourse()
  118. {
  119. if (Session::read('login_as')) {
  120. return false;
  121. }
  122. $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  123. // For "what's new" notification
  124. $TABLETRACK_LASTACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  125. $sessionId = api_get_session_id();
  126. $now = api_get_utc_datetime();
  127. $courseId = api_get_course_int_id();
  128. $userId = api_get_user_id();
  129. $ip = Database::escape_string(api_get_real_ip());
  130. if (self::isSessionLogNeedToBeSave($sessionId) === false) {
  131. return false;
  132. }
  133. if ($userId) {
  134. $userId = $userId;
  135. } else {
  136. $userId = '0'; // no one
  137. }
  138. $sql = "INSERT INTO $TABLETRACK_ACCESS (user_ip, access_user_id, c_id, access_date, access_session_id)
  139. VALUES ('$ip', $userId, $courseId, '$now', $sessionId)";
  140. Database::query($sql);
  141. // added for "what's new" notification
  142. $sql = "UPDATE $TABLETRACK_LASTACCESS SET access_date = '$now'
  143. WHERE
  144. access_user_id = $userId AND
  145. c_id = $courseId AND
  146. access_tool IS NULL AND
  147. access_session_id = $sessionId";
  148. $result = Database::query($sql);
  149. if (Database::affected_rows($result) == 0) {
  150. $sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id, c_id, access_date, access_session_id)
  151. VALUES ($userId, $courseId, '$now', $sessionId)";
  152. Database::query($sql);
  153. }
  154. return true;
  155. }
  156. /**
  157. * @param string $tool name of the tool
  158. *
  159. * @author Sebastien Piraux <piraux_seb@hotmail.com>
  160. * @desc Record information for access event for tools
  161. *
  162. * $tool can take this values :
  163. * Links, Calendar, Document, Announcements,
  164. * Group, Video, Works, Users, Exercises, Course Desc
  165. * ...
  166. * Values can be added if new modules are created (15char max)
  167. * I encourage to use $nameTool as $tool when calling this function
  168. *
  169. * Functionality for "what's new" notification is added by Toon Van Hoecke
  170. *
  171. * @return bool
  172. */
  173. public static function event_access_tool($tool)
  174. {
  175. if (Session::read('login_as')) {
  176. return false;
  177. }
  178. $tool = Database::escape_string($tool);
  179. if (empty($tool)) {
  180. return false;
  181. }
  182. $courseInfo = api_get_course_info();
  183. $sessionId = api_get_session_id();
  184. $reallyNow = api_get_utc_datetime();
  185. $userId = api_get_user_id();
  186. if (empty($courseInfo)) {
  187. return false;
  188. }
  189. if (self::isSessionLogNeedToBeSave($sessionId) === false) {
  190. return false;
  191. }
  192. $courseId = $courseInfo['real_id'];
  193. $tableAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  194. //for "what's new" notification
  195. $tableLastAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  196. // record information
  197. // only if user comes from the course $_cid
  198. //if( eregi($_configuration['root_web'].$_cid,$_SERVER['HTTP_REFERER'] ) )
  199. //$pos = strpos($_SERVER['HTTP_REFERER'],$_configuration['root_web'].$_cid);
  200. $coursePath = isset($courseInfo['path']) ? $courseInfo['path'] : null;
  201. $pos = isset($_SERVER['HTTP_REFERER']) ? strpos(strtolower($_SERVER['HTTP_REFERER']), strtolower(api_get_path(WEB_COURSE_PATH).$coursePath)) : false;
  202. // added for "what's new" notification
  203. $pos2 = isset($_SERVER['HTTP_REFERER']) ? strpos(strtolower($_SERVER['HTTP_REFERER']), strtolower(api_get_path(WEB_PATH)."index")) : false;
  204. // end "what's new" notification
  205. if ($pos !== false || $pos2 !== false) {
  206. $params = [
  207. 'access_user_id' => $userId,
  208. 'c_id' => $courseId,
  209. 'access_tool' => $tool,
  210. 'access_date' => $reallyNow,
  211. 'access_session_id' => $sessionId,
  212. 'user_ip' => Database::escape_string(api_get_real_ip()),
  213. ];
  214. Database::insert($tableAccess, $params);
  215. }
  216. // "what's new" notification
  217. $sql = "UPDATE $tableLastAccess
  218. SET access_date = '$reallyNow'
  219. WHERE
  220. access_user_id = $userId AND
  221. c_id = $courseId AND
  222. access_tool = '$tool' AND
  223. access_session_id = $sessionId";
  224. $result = Database::query($sql);
  225. if (Database::affected_rows($result) == 0) {
  226. $params = [
  227. 'access_user_id' => $userId,
  228. 'c_id' => $courseId,
  229. 'access_tool' => $tool,
  230. 'access_date' => $reallyNow,
  231. 'access_session_id' => $sessionId,
  232. ];
  233. Database::insert($tableLastAccess, $params);
  234. }
  235. return true;
  236. }
  237. /**
  238. * Record information for download event (when an user click to d/l a
  239. * document) it will be used in a redirection page.
  240. *
  241. * @param string $documentUrl
  242. *
  243. * @return int
  244. *
  245. * @author Sebastien Piraux <piraux_seb@hotmail.com>
  246. * @author Evie Embrechts (bug fixed: The user id is put in single quotes)
  247. */
  248. public static function event_download($documentUrl)
  249. {
  250. if (Session::read('login_as')) {
  251. return false;
  252. }
  253. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  254. $documentUrl = Database::escape_string($documentUrl);
  255. $reallyNow = api_get_utc_datetime();
  256. $userId = api_get_user_id();
  257. $courseId = api_get_course_int_id();
  258. $sessionId = api_get_session_id();
  259. $sql = "INSERT INTO $table (
  260. down_user_id,
  261. c_id,
  262. down_doc_path,
  263. down_date,
  264. down_session_id
  265. )
  266. VALUES (
  267. $userId,
  268. $courseId,
  269. '$documentUrl',
  270. '$reallyNow',
  271. $sessionId
  272. )";
  273. Database::query($sql);
  274. return 1;
  275. }
  276. /**
  277. * @param int $documentId of document (id in mainDb.document table)
  278. *
  279. * @author Sebastien Piraux <piraux_seb@hotmail.com>
  280. * @desc Record information for upload event
  281. * used in the works tool to record informations when
  282. * an user upload 1 work
  283. *
  284. * @return int
  285. */
  286. public static function event_upload($documentId)
  287. {
  288. if (Session::read('login_as')) {
  289. return false;
  290. }
  291. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
  292. $courseId = api_get_course_int_id();
  293. $reallyNow = api_get_utc_datetime();
  294. $userId = api_get_user_id();
  295. $documentId = (int) $documentId;
  296. $sessionId = api_get_session_id();
  297. $sql = "INSERT INTO $table
  298. ( upload_user_id,
  299. c_id,
  300. upload_cours_id,
  301. upload_work_id,
  302. upload_date,
  303. upload_session_id
  304. )
  305. VALUES (
  306. $userId,
  307. $courseId,
  308. '',
  309. $documentId,
  310. '$reallyNow',
  311. $sessionId
  312. )";
  313. Database::query($sql);
  314. return 1;
  315. }
  316. /**
  317. * Record information for link event (when an user click on an added link)
  318. * it will be used in a redirection page.
  319. *
  320. * @param int $linkId (id in c_link table)
  321. *
  322. * @return int
  323. *
  324. * @author Sebastien Piraux <piraux_seb@hotmail.com>
  325. */
  326. public static function event_link($linkId)
  327. {
  328. if (Session::read('login_as')) {
  329. return false;
  330. }
  331. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  332. $reallyNow = api_get_utc_datetime();
  333. $userId = api_get_user_id();
  334. $courseId = api_get_course_int_id();
  335. $linkId = (int) $linkId;
  336. $sessionId = api_get_session_id();
  337. $sql = "INSERT INTO ".$table."
  338. ( links_user_id,
  339. c_id,
  340. links_link_id,
  341. links_date,
  342. links_session_id
  343. ) VALUES (
  344. $userId,
  345. $courseId,
  346. $linkId,
  347. '$reallyNow',
  348. $sessionId
  349. )";
  350. Database::query($sql);
  351. return 1;
  352. }
  353. /**
  354. * Update the TRACK_E_EXERCICES exercises.
  355. *
  356. * @param int exeid id of the attempt
  357. * @param int exo_id exercise id
  358. * @param mixed result score
  359. * @param int weighting ( higher score )
  360. * @param int duration ( duration of the attempt in seconds )
  361. * @param int session_id
  362. * @param int learnpath_id (id of the learnpath)
  363. * @param int learnpath_item_id (id of the learnpath_item)
  364. *
  365. * @return bool
  366. *
  367. * @author Sebastien Piraux <piraux_seb@hotmail.com>
  368. * @author Julio Montoya Armas <gugli100@gmail.com> Reworked 2010
  369. * @desc Record result of user when an exercise was done
  370. */
  371. public static function updateEventExercise(
  372. $exeId,
  373. $exoId,
  374. $score,
  375. $weighting,
  376. $sessionId,
  377. $learnpathId = 0,
  378. $learnpathItemId = 0,
  379. $learnpathItemViewId = 0,
  380. $duration = 0,
  381. $questionsList = [],
  382. $status = '',
  383. $remindList = [],
  384. $endDate = null
  385. ) {
  386. if (empty($exeId)) {
  387. return false;
  388. }
  389. /*
  390. * Code commented due BT#8423 do not change the score to 0.
  391. *
  392. * Validation in case of fraud with actived control time
  393. if (!ExerciseLib::exercise_time_control_is_valid($exo_id, $learnpath_id, $learnpath_item_id)) {
  394. $score = 0;
  395. }
  396. */
  397. if (!isset($status) || empty($status)) {
  398. $status = '';
  399. } else {
  400. $status = Database::escape_string($status);
  401. }
  402. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  403. if (!empty($questionsList)) {
  404. $questionsList = array_map('intval', $questionsList);
  405. }
  406. if (!empty($remindList)) {
  407. $remindList = array_map('intval', $remindList);
  408. $remindList = array_filter($remindList);
  409. $remindList = implode(",", $remindList);
  410. } else {
  411. $remindList = '';
  412. }
  413. if (empty($endDate)) {
  414. $endDate = api_get_utc_datetime();
  415. }
  416. $exoId = (int) $exoId;
  417. $sessionId = (int) $sessionId;
  418. $learnpathId = (int) $learnpathId;
  419. $learnpathItemId = (int) $learnpathItemId;
  420. $learnpathItemViewId = (int) $learnpathItemViewId;
  421. $duration = (int) $duration;
  422. $exeId = (int) $exeId;
  423. $score = Database::escape_string($score);
  424. $weighting = Database::escape_string($weighting);
  425. $questions = implode(',', $questionsList);
  426. $userIp = Database::escape_string(api_get_real_ip());
  427. $sql = "UPDATE $table SET
  428. exe_exo_id = $exoId,
  429. exe_result = '$score',
  430. exe_weighting = '$weighting',
  431. session_id = $sessionId,
  432. orig_lp_id = $learnpathId,
  433. orig_lp_item_id = $learnpathItemId,
  434. orig_lp_item_view_id = $learnpathItemViewId,
  435. exe_duration = $duration,
  436. exe_date = '$endDate',
  437. status = '$status',
  438. questions_to_check = '$remindList',
  439. data_tracking = '$questions',
  440. user_ip = '$userIp'
  441. WHERE exe_id = $exeId";
  442. Database::query($sql);
  443. //Deleting control time session track
  444. //ExerciseLib::exercise_time_control_delete($exo_id);
  445. return true;
  446. }
  447. /**
  448. * Record an event for this attempt at answering an exercise.
  449. *
  450. * @param float Score achieved
  451. * @param string Answer given
  452. * @param int Question ID
  453. * @param int Exercise attempt ID a.k.a exe_id (from track_e_exercise)
  454. * @param int Position
  455. * @param int Exercise ID (from c_quiz)
  456. * @param bool update results?
  457. * @param $fileName string Filename (for audio answers - using nanogong)
  458. * @param int User ID The user who's going to get this score. Default value of null means "get from context".
  459. * @param int Course ID (from the "id" column of course table). Default value of null means "get from context".
  460. * @param int Session ID (from the session table). Default value of null means "get from context".
  461. * @param int Learnpath ID (from c_lp table). Default value of null means "get from context".
  462. * @param int Learnpath item ID (from the c_lp_item table). Default value of null means "get from context".
  463. *
  464. * @return bool Result of the insert query
  465. */
  466. public static function saveQuestionAttempt(
  467. $score,
  468. $answer,
  469. $question_id,
  470. $exe_id,
  471. $position,
  472. $exercise_id = 0,
  473. $updateResults = false,
  474. $fileName = null,
  475. $user_id = null,
  476. $course_id = null,
  477. $session_id = null,
  478. $learnpath_id = null,
  479. $learnpath_item_id = null
  480. ) {
  481. global $debug;
  482. $question_id = Database::escape_string($question_id);
  483. $exe_id = Database::escape_string($exe_id);
  484. $position = Database::escape_string($position);
  485. $now = api_get_utc_datetime();
  486. $course_id = (int) $course_id;
  487. // check user_id or get from context
  488. if (empty($user_id)) {
  489. $user_id = api_get_user_id();
  490. // anonymous
  491. if (empty($user_id)) {
  492. $user_id = api_get_anonymous_id();
  493. }
  494. }
  495. // check course_id or get from context
  496. if (empty($course_id)) {
  497. $course_id = api_get_course_int_id();
  498. }
  499. // check session_id or get from context
  500. $session_id = (int) $session_id;
  501. if (empty($session_id)) {
  502. $session_id = api_get_session_id();
  503. }
  504. // check learnpath_id or get from context
  505. if (empty($learnpath_id)) {
  506. global $learnpath_id;
  507. }
  508. // check learnpath_item_id or get from context
  509. if (empty($learnpath_item_id)) {
  510. global $learnpath_item_id;
  511. }
  512. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  513. if ($debug) {
  514. error_log("----- entering saveQuestionAttempt() function ------");
  515. error_log("answer: $answer");
  516. error_log("score: $score");
  517. error_log("question_id : $question_id");
  518. error_log("position: $position");
  519. }
  520. //Validation in case of fraud with active control time
  521. if (!ExerciseLib::exercise_time_control_is_valid($exercise_id, $learnpath_id, $learnpath_item_id)) {
  522. if ($debug) {
  523. error_log("exercise_time_control_is_valid is false");
  524. }
  525. $score = 0;
  526. $answer = 0;
  527. }
  528. if (!empty($question_id) && !empty($exe_id) && !empty($user_id)) {
  529. if (is_null($answer)) {
  530. $answer = '';
  531. }
  532. if (is_null($score)) {
  533. $score = 0;
  534. }
  535. $attempt = [
  536. 'user_id' => $user_id,
  537. 'question_id' => $question_id,
  538. 'answer' => $answer,
  539. 'marks' => $score,
  540. 'c_id' => $course_id,
  541. 'session_id' => $session_id,
  542. 'position' => $position,
  543. 'tms' => $now,
  544. 'filename' => !empty($fileName) ? basename($fileName) : $fileName,
  545. 'teacher_comment' => '',
  546. ];
  547. // Check if attempt exists.
  548. $sql = "SELECT exe_id FROM $TBL_TRACK_ATTEMPT
  549. WHERE
  550. c_id = $course_id AND
  551. session_id = $session_id AND
  552. exe_id = $exe_id AND
  553. user_id = $user_id AND
  554. question_id = $question_id AND
  555. position = $position";
  556. $result = Database::query($sql);
  557. if (Database::num_rows($result)) {
  558. if ($debug) {
  559. error_log("Attempt already exist: exe_id: $exe_id - user_id:$user_id - question_id:$question_id");
  560. }
  561. if ($updateResults == false) {
  562. //The attempt already exist do not update use update_event_exercise() instead
  563. return false;
  564. }
  565. } else {
  566. $attempt['exe_id'] = $exe_id;
  567. }
  568. if ($debug) {
  569. error_log("updateResults : $updateResults");
  570. error_log("Saving question attempt: ");
  571. error_log($sql);
  572. }
  573. $recording_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  574. if ($updateResults == false) {
  575. $attempt_id = Database::insert($TBL_TRACK_ATTEMPT, $attempt);
  576. if ($debug) {
  577. error_log("Insert attempt with id #$attempt_id");
  578. }
  579. if (defined('ENABLED_LIVE_EXERCISE_TRACKING')) {
  580. if ($debug) {
  581. error_log("Saving e attempt recording ");
  582. }
  583. $attempt_recording = [
  584. 'exe_id' => $attempt_id,
  585. 'question_id' => $question_id,
  586. 'marks' => $score,
  587. 'insert_date' => $now,
  588. 'author' => '',
  589. 'session_id' => $session_id,
  590. ];
  591. Database::insert($recording_table, $attempt_recording);
  592. }
  593. } else {
  594. Database::update(
  595. $TBL_TRACK_ATTEMPT,
  596. $attempt,
  597. [
  598. 'exe_id = ? AND question_id = ? AND user_id = ? ' => [
  599. $exe_id,
  600. $question_id,
  601. $user_id,
  602. ],
  603. ]
  604. );
  605. if (defined('ENABLED_LIVE_EXERCISE_TRACKING')) {
  606. $attempt_recording = [
  607. 'exe_id' => $exe_id,
  608. 'question_id' => $question_id,
  609. 'marks' => $score,
  610. 'insert_date' => $now,
  611. 'author' => '',
  612. 'session_id' => $session_id,
  613. ];
  614. Database::update(
  615. $recording_table,
  616. $attempt_recording,
  617. [
  618. 'exe_id = ? AND question_id = ? AND session_id = ? ' => [
  619. $exe_id,
  620. $question_id,
  621. $session_id,
  622. ],
  623. ]
  624. );
  625. }
  626. $attempt_id = $exe_id;
  627. }
  628. return $attempt_id;
  629. } else {
  630. return false;
  631. }
  632. }
  633. /**
  634. * Record an hotspot spot for this attempt at answering an hotspot question.
  635. *
  636. * @param int $exeId
  637. * @param int $questionId Question ID
  638. * @param int $answerId Answer ID
  639. * @param int $correct
  640. * @param string $coords Coordinates of this point (e.g. 123;324)
  641. * @param bool $updateResults
  642. * @param int $exerciseId
  643. *
  644. * @return bool Result of the insert query
  645. *
  646. * @uses \Course code and user_id from global scope $_cid and $_user
  647. */
  648. public static function saveExerciseAttemptHotspot(
  649. $exeId,
  650. $questionId,
  651. $answerId,
  652. $correct,
  653. $coords,
  654. $updateResults = false,
  655. $exerciseId = 0
  656. ) {
  657. $debug = false;
  658. global $safe_lp_id, $safe_lp_item_id;
  659. if ($updateResults == false) {
  660. // Validation in case of fraud with activated control time
  661. if (!ExerciseLib::exercise_time_control_is_valid($exerciseId, $safe_lp_id, $safe_lp_item_id)) {
  662. if ($debug) {
  663. error_log('Attempt is fraud');
  664. }
  665. $correct = 0;
  666. }
  667. }
  668. if (empty($exeId)) {
  669. if ($debug) {
  670. error_log('exe id is empty');
  671. }
  672. return false;
  673. }
  674. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  675. if ($updateResults) {
  676. if ($debug) {
  677. error_log("Insert hotspot results: exeId: $exeId correct: $correct");
  678. }
  679. $params = [
  680. 'hotspot_correct' => $correct,
  681. 'hotspot_coordinate' => $coords,
  682. ];
  683. Database::update(
  684. $table,
  685. $params,
  686. [
  687. 'hotspot_user_id = ? AND hotspot_exe_id = ? AND hotspot_question_id = ? AND hotspot_answer_id = ? ' => [
  688. api_get_user_id(),
  689. $exeId,
  690. $questionId,
  691. $answerId,
  692. ],
  693. ]
  694. );
  695. } else {
  696. if ($debug) {
  697. error_log("Insert hotspot results: exeId: $exeId correct: $correct");
  698. }
  699. return Database::insert(
  700. $table,
  701. [
  702. 'hotspot_course_code' => api_get_course_id(),
  703. 'hotspot_user_id' => api_get_user_id(),
  704. 'c_id' => api_get_course_int_id(),
  705. 'hotspot_exe_id' => $exeId,
  706. 'hotspot_question_id' => $questionId,
  707. 'hotspot_answer_id' => $answerId,
  708. 'hotspot_correct' => $correct,
  709. 'hotspot_coordinate' => $coords,
  710. ]
  711. );
  712. }
  713. }
  714. /**
  715. * Records information for common (or admin) events (in the track_e_default table).
  716. *
  717. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  718. *
  719. * @param string $event_type Type of event
  720. * @param string $event_value_type Type of value
  721. * @param mixed $event_value Value (string, or array in the case of user info)
  722. * @param string $datetime Datetime (UTC) (defaults to null)
  723. * @param int $user_id User ID (defaults to null)
  724. * @param int $course_id Course ID (defaults to null)
  725. * @param int $sessionId Session ID
  726. *
  727. * @return bool
  728. * @assert ('','','') === false
  729. */
  730. public static function addEvent(
  731. $event_type,
  732. $event_value_type,
  733. $event_value,
  734. $datetime = null,
  735. $user_id = null,
  736. $course_id = null,
  737. $sessionId = 0
  738. ) {
  739. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  740. if (empty($event_type)) {
  741. return false;
  742. }
  743. $event_type = Database::escape_string($event_type);
  744. $event_value_type = Database::escape_string($event_value_type);
  745. if (!empty($course_id)) {
  746. $course_id = (int) $course_id;
  747. } else {
  748. $course_id = api_get_course_int_id();
  749. }
  750. if (!empty($sessionId)) {
  751. $sessionId = (int) $sessionId;
  752. } else {
  753. $sessionId = api_get_session_id();
  754. }
  755. //Clean the user_info
  756. if ($event_value_type == LOG_USER_OBJECT) {
  757. if (is_array($event_value)) {
  758. unset($event_value['complete_name']);
  759. unset($event_value['complete_name_with_username']);
  760. unset($event_value['firstName']);
  761. unset($event_value['lastName']);
  762. unset($event_value['avatar_small']);
  763. unset($event_value['avatar']);
  764. unset($event_value['mail']);
  765. unset($event_value['password']);
  766. unset($event_value['last_login']);
  767. unset($event_value['picture_uri']);
  768. $event_value = serialize($event_value);
  769. }
  770. }
  771. // If event is an array then the $event_value_type should finish with
  772. // the suffix _array for example LOG_WORK_DATA = work_data_array
  773. if (is_array($event_value)) {
  774. $event_value = serialize($event_value);
  775. }
  776. $event_value = Database::escape_string($event_value);
  777. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  778. if (!isset($datetime)) {
  779. $datetime = api_get_utc_datetime();
  780. }
  781. $datetime = Database::escape_string($datetime);
  782. if (!isset($user_id)) {
  783. $user_id = api_get_user_id();
  784. }
  785. $params = [
  786. 'default_user_id' => $user_id,
  787. 'c_id' => $course_id,
  788. 'default_date' => $datetime,
  789. 'default_event_type' => $event_type,
  790. 'default_value_type' => $event_value_type,
  791. 'default_value' => $event_value,
  792. 'session_id' => $sessionId,
  793. ];
  794. Database::insert($table, $params);
  795. return true;
  796. }
  797. /**
  798. * Get every email stored in the database.
  799. *
  800. * @deprecated
  801. *
  802. * @return array
  803. * @assert () !== false
  804. */
  805. public static function get_all_event_types()
  806. {
  807. global $event_config;
  808. $sql = 'SELECT etm.id, event_type_name, activated, language_id, message, subject, dokeos_folder
  809. FROM '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' etm
  810. INNER JOIN '.Database::get_main_table(TABLE_MAIN_LANGUAGE).' l
  811. ON etm.language_id = l.id';
  812. $events_types = Database::store_result(Database::query($sql), 'ASSOC');
  813. $to_return = [];
  814. foreach ($events_types as $et) {
  815. $et['nameLangVar'] = $event_config[$et["event_type_name"]]["name_lang_var"];
  816. $et['descLangVar'] = $event_config[$et["event_type_name"]]["desc_lang_var"];
  817. $to_return[] = $et;
  818. }
  819. return $to_return;
  820. }
  821. /**
  822. * Get the users related to one event.
  823. *
  824. * @param string $event_name
  825. *
  826. * @return string
  827. */
  828. public static function get_event_users($event_name)
  829. {
  830. $event_name = Database::escape_string($event_name);
  831. $sql = 'SELECT user.user_id, user.firstname, user.lastname
  832. FROM '.Database::get_main_table(TABLE_MAIN_USER).' user
  833. JOIN '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' relUser
  834. ON relUser.user_id = user.user_id
  835. WHERE user.status <> '.ANONYMOUS.' AND relUser.event_type_name = "'.$event_name.'"';
  836. $user_list = Database::store_result(Database::query($sql), 'ASSOC');
  837. return json_encode($user_list);
  838. }
  839. /**
  840. * @param int $user_id
  841. * @param string $event_type
  842. *
  843. * @return array|bool
  844. */
  845. public static function get_events_by_user_and_type($user_id, $event_type)
  846. {
  847. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  848. $user_id = (int) $user_id;
  849. $event_type = Database::escape_string($event_type);
  850. $sql = "SELECT * FROM $table
  851. WHERE default_value_type = 'user_id' AND
  852. default_value = $user_id AND
  853. default_event_type = '$event_type'
  854. ORDER BY default_date ";
  855. $result = Database::query($sql);
  856. if ($result) {
  857. return Database::store_result($result, 'ASSOC');
  858. }
  859. return false;
  860. }
  861. /**
  862. * Save the new message for one event and for one language.
  863. *
  864. * @param string $event_name
  865. * @param array $users
  866. * @param string $message
  867. * @param string $subject
  868. * @param string $event_message_language
  869. * @param int $activated
  870. */
  871. public static function save_event_type_message(
  872. $event_name,
  873. $users,
  874. $message,
  875. $subject,
  876. $event_message_language,
  877. $activated
  878. ) {
  879. $event_name = Database::escape_string($event_name);
  880. $activated = (int) $activated;
  881. $event_message_language = Database::escape_string($event_message_language);
  882. // Deletes then re-adds the users linked to the event
  883. $sql = 'DELETE FROM '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).'
  884. WHERE event_type_name = "'.$event_name.'" ';
  885. Database::query($sql);
  886. $eventTable = Database::get_main_table(TABLE_EVENT_TYPE_REL_USER);
  887. foreach ($users as $user) {
  888. $user = (int) $user;
  889. $sql = "INSERT INTO $eventTable (user_id,event_type_name)
  890. VALUES($user,'$event_name')";
  891. Database::query($sql);
  892. }
  893. $language_id = api_get_language_id($event_message_language);
  894. // check if this template in this language already exists or not
  895. $eventMailTable = Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE);
  896. $sql = "SELECT COUNT(id) as total
  897. FROM $eventMailTable
  898. WHERE event_type_name = '$event_name' AND language_id = $language_id";
  899. $sql = Database::store_result(Database::query($sql), 'ASSOC');
  900. $languageTable = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  901. $message = Database::escape_string($message);
  902. $subject = Database::escape_string($subject);
  903. // if already exists, we update
  904. if ($sql[0]["total"] > 0) {
  905. $sql = "UPDATE $eventMailTable
  906. SET message = '$message',
  907. subject = '$subject',
  908. activated = $activated
  909. WHERE event_type_name = '$event_name' AND language_id = (
  910. SELECT id FROM $languageTable
  911. WHERE dokeos_folder = '$event_message_language'
  912. )";
  913. Database::query($sql);
  914. } else { // else we create a new record
  915. // gets the language_-_id
  916. $lang_id = "(SELECT id FROM $languageTable
  917. WHERE dokeos_folder = '$event_message_language')";
  918. $lang_id = Database::store_result(Database::query($lang_id), 'ASSOC');
  919. $lang_id = $lang_id[0]['id'];
  920. if (!empty($lang_id[0]["id"])) {
  921. $sql = "INSERT INTO $eventMailTable (event_type_name, language_id, message, subject, activated)
  922. VALUES ('$event_name', $lang_id, '$message', '$subject', $activated)";
  923. Database::query($sql);
  924. }
  925. }
  926. // set activated at every save
  927. $sql = "UPDATE $eventMailTable
  928. SET activated = $activated
  929. WHERE event_type_name = '$event_name'";
  930. Database::query($sql);
  931. }
  932. /**
  933. * Gets the last attempt of an exercise based in the exe_id.
  934. *
  935. * @param int $exeId
  936. *
  937. * @return mixed
  938. */
  939. public static function getLastAttemptDateOfExercise($exeId)
  940. {
  941. $exeId = (int) $exeId;
  942. $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  943. $sql = "SELECT max(tms) as last_attempt_date
  944. FROM $track_attempts
  945. WHERE exe_id = $exeId";
  946. $rs_last_attempt = Database::query($sql);
  947. $row_last_attempt = Database::fetch_array($rs_last_attempt);
  948. $date = $row_last_attempt['last_attempt_date']; //Get the date of last attempt
  949. return $date;
  950. }
  951. /**
  952. * Gets the last attempt of an exercise based in the exe_id.
  953. *
  954. * @param int $exeId
  955. *
  956. * @return mixed
  957. */
  958. public static function getLatestQuestionIdFromAttempt($exeId)
  959. {
  960. $exeId = (int) $exeId;
  961. $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  962. $sql = "SELECT question_id FROM $track_attempts
  963. WHERE exe_id = $exeId
  964. ORDER BY tms DESC
  965. LIMIT 1";
  966. $result = Database::query($sql);
  967. if (Database::num_rows($result)) {
  968. $row = Database::fetch_array($result);
  969. return $row['question_id'];
  970. } else {
  971. return false;
  972. }
  973. }
  974. /**
  975. * Gets how many attempts exists by user, exercise, learning path.
  976. *
  977. * @param int user id
  978. * @param int exercise id
  979. * @param int lp id
  980. * @param int lp item id
  981. * @param int lp item view id
  982. *
  983. * @return int
  984. */
  985. public static function get_attempt_count(
  986. $user_id,
  987. $exerciseId,
  988. $lp_id,
  989. $lp_item_id,
  990. $lp_item_view_id
  991. ) {
  992. $stat_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  993. $user_id = (int) $user_id;
  994. $exerciseId = (int) $exerciseId;
  995. $lp_id = (int) $lp_id;
  996. $lp_item_id = (int) $lp_item_id;
  997. $lp_item_view_id = (int) $lp_item_view_id;
  998. $courseId = api_get_course_int_id();
  999. $sessionId = api_get_session_id();
  1000. $sql = "SELECT count(*) as count
  1001. FROM $stat_table
  1002. WHERE
  1003. exe_exo_id = $exerciseId AND
  1004. exe_user_id = $user_id AND
  1005. status != 'incomplete' AND
  1006. orig_lp_id = $lp_id AND
  1007. orig_lp_item_id = $lp_item_id AND
  1008. orig_lp_item_view_id = $lp_item_view_id AND
  1009. c_id = $courseId AND
  1010. session_id = $sessionId";
  1011. $query = Database::query($sql);
  1012. if (Database::num_rows($query) > 0) {
  1013. $attempt = Database::fetch_array($query, 'ASSOC');
  1014. return (int) $attempt['count'];
  1015. }
  1016. return 0;
  1017. }
  1018. /**
  1019. * @param $user_id
  1020. * @param $exerciseId
  1021. * @param $lp_id
  1022. * @param $lp_item_id
  1023. *
  1024. * @return int
  1025. */
  1026. public static function get_attempt_count_not_finished(
  1027. $user_id,
  1028. $exerciseId,
  1029. $lp_id,
  1030. $lp_item_id
  1031. ) {
  1032. $stat_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1033. $user_id = (int) $user_id;
  1034. $exerciseId = (int) $exerciseId;
  1035. $lp_id = (int) $lp_id;
  1036. $lp_item_id = (int) $lp_item_id;
  1037. //$lp_item_view_id = (int) $lp_item_view_id;
  1038. $courseId = api_get_course_int_id();
  1039. $sessionId = api_get_session_id();
  1040. $sql = "SELECT count(*) as count
  1041. FROM $stat_table
  1042. WHERE
  1043. exe_exo_id = $exerciseId AND
  1044. exe_user_id = $user_id AND
  1045. status != 'incomplete' AND
  1046. orig_lp_id = $lp_id AND
  1047. orig_lp_item_id = $lp_item_id AND
  1048. c_id = $courseId AND
  1049. session_id = $sessionId";
  1050. $query = Database::query($sql);
  1051. if (Database::num_rows($query) > 0) {
  1052. $attempt = Database::fetch_array($query, 'ASSOC');
  1053. return $attempt['count'];
  1054. } else {
  1055. return 0;
  1056. }
  1057. }
  1058. /**
  1059. * @param int $user_id
  1060. * @param int $lp_id
  1061. * @param array $course
  1062. * @param int $session_id
  1063. *
  1064. * @return bool
  1065. */
  1066. public static function delete_student_lp_events(
  1067. $user_id,
  1068. $lp_id,
  1069. $course,
  1070. $session_id
  1071. ) {
  1072. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  1073. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  1074. $lpInteraction = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  1075. $lpObjective = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  1076. if (empty($course)) {
  1077. return false;
  1078. }
  1079. $course_id = $course['real_id'];
  1080. $user_id = (int) $user_id;
  1081. $lp_id = (int) $lp_id;
  1082. $session_id = (int) $session_id;
  1083. if (empty($course_id)) {
  1084. $course_id = api_get_course_int_id();
  1085. }
  1086. $track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1087. $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1088. $recording_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  1089. // Make sure we have the exact lp_view_id
  1090. $sql = "SELECT id FROM $lp_view_table
  1091. WHERE
  1092. c_id = $course_id AND
  1093. user_id = $user_id AND
  1094. lp_id = $lp_id AND
  1095. session_id = $session_id";
  1096. $result = Database::query($sql);
  1097. if (Database::num_rows($result)) {
  1098. $view = Database::fetch_array($result, 'ASSOC');
  1099. $lp_view_id = $view['id'];
  1100. $sql = "DELETE FROM $lp_item_view_table
  1101. WHERE c_id = $course_id AND lp_view_id = $lp_view_id";
  1102. Database::query($sql);
  1103. $sql = "DELETE FROM $lpInteraction
  1104. WHERE c_id = $course_id AND lp_iv_id = $lp_view_id";
  1105. Database::query($sql);
  1106. $sql = "DELETE FROM $lpObjective
  1107. WHERE c_id = $course_id AND lp_iv_id = $lp_view_id";
  1108. Database::query($sql);
  1109. }
  1110. if (api_get_configuration_value('lp_minimum_time')) {
  1111. $sql = "DELETE FROM track_e_access_complete
  1112. WHERE
  1113. tool = 'learnpath' AND
  1114. c_id = $course_id AND
  1115. tool_id = $lp_id AND
  1116. user_id = $user_id AND
  1117. session_id = $session_id
  1118. ";
  1119. Database::query($sql);
  1120. }
  1121. $sql = "DELETE FROM $lp_view_table
  1122. WHERE
  1123. c_id = $course_id AND
  1124. user_id = $user_id AND
  1125. lp_id= $lp_id AND
  1126. session_id = $session_id
  1127. ";
  1128. Database::query($sql);
  1129. $sql = "SELECT exe_id FROM $track_e_exercises
  1130. WHERE
  1131. exe_user_id = $user_id AND
  1132. session_id = $session_id AND
  1133. c_id = $course_id AND
  1134. orig_lp_id = $lp_id";
  1135. $result = Database::query($sql);
  1136. $exe_list = [];
  1137. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1138. $exe_list[] = $row['exe_id'];
  1139. }
  1140. if (!empty($exe_list) && is_array($exe_list) && count($exe_list) > 0) {
  1141. $exeListString = implode(',', $exe_list);
  1142. $sql = "DELETE FROM $track_e_exercises
  1143. WHERE exe_id IN ($exeListString)";
  1144. Database::query($sql);
  1145. $sql = "DELETE FROM $track_attempts
  1146. WHERE exe_id IN ($exeListString)";
  1147. Database::query($sql);
  1148. $sql = "DELETE FROM $recording_table
  1149. WHERE exe_id IN ($exeListString)";
  1150. Database::query($sql);
  1151. }
  1152. self::addEvent(
  1153. LOG_LP_ATTEMPT_DELETE,
  1154. LOG_LP_ID,
  1155. $lp_id,
  1156. null,
  1157. null,
  1158. $course_id,
  1159. $session_id
  1160. );
  1161. return true;
  1162. }
  1163. /**
  1164. * Delete all exercise attempts (included in LP or not).
  1165. *
  1166. * @param int user id
  1167. * @param int exercise id
  1168. * @param int $course_id
  1169. * @param int session id
  1170. */
  1171. public static function delete_all_incomplete_attempts(
  1172. $user_id,
  1173. $exercise_id,
  1174. $course_id,
  1175. $session_id = 0
  1176. ) {
  1177. $user_id = (int) $user_id;
  1178. $exercise_id = (int) $exercise_id;
  1179. $course_id = (int) $course_id;
  1180. $session_id = (int) $session_id;
  1181. if (!empty($user_id) && !empty($exercise_id) && !empty($course_id)) {
  1182. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1183. $sql = "DELETE FROM $table
  1184. WHERE
  1185. exe_user_id = $user_id AND
  1186. exe_exo_id = $exercise_id AND
  1187. c_id = $course_id AND
  1188. session_id = $session_id AND
  1189. status = 'incomplete' ";
  1190. Database::query($sql);
  1191. self::addEvent(
  1192. LOG_EXERCISE_RESULT_DELETE,
  1193. LOG_EXERCISE_AND_USER_ID,
  1194. $exercise_id.'-'.$user_id,
  1195. null,
  1196. null,
  1197. $course_id,
  1198. $session_id
  1199. );
  1200. }
  1201. }
  1202. /**
  1203. * Gets all exercise results (NO Exercises in LPs ) from a given exercise id, course, session.
  1204. *
  1205. * @param int $exercise_id
  1206. * @param int $courseId
  1207. * @param int $session_id
  1208. *
  1209. * @return array with the results
  1210. */
  1211. public static function get_all_exercise_results(
  1212. $exercise_id,
  1213. $courseId,
  1214. $session_id = 0,
  1215. $load_question_list = true,
  1216. $user_id = null
  1217. ) {
  1218. $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1219. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1220. $courseId = (int) $courseId;
  1221. $exercise_id = (int) $exercise_id;
  1222. $session_id = (int) $session_id;
  1223. $user_condition = null;
  1224. if (!empty($user_id)) {
  1225. $user_id = (int) $user_id;
  1226. $user_condition = "AND exe_user_id = $user_id ";
  1227. }
  1228. $sql = "SELECT * FROM $TABLETRACK_EXERCICES
  1229. WHERE
  1230. status = '' AND
  1231. c_id = $courseId AND
  1232. exe_exo_id = $exercise_id AND
  1233. session_id = $session_id AND
  1234. orig_lp_id =0 AND
  1235. orig_lp_item_id = 0
  1236. $user_condition
  1237. ORDER BY exe_id";
  1238. $res = Database::query($sql);
  1239. $list = [];
  1240. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1241. $list[$row['exe_id']] = $row;
  1242. if ($load_question_list) {
  1243. $sql = "SELECT * FROM $TBL_TRACK_ATTEMPT
  1244. WHERE exe_id = {$row['exe_id']}";
  1245. $res_question = Database::query($sql);
  1246. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1247. $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q;
  1248. }
  1249. }
  1250. }
  1251. return $list;
  1252. }
  1253. /**
  1254. * Gets all exercise results (NO Exercises in LPs ) from a given exercise id, course, session.
  1255. *
  1256. * @param int $courseId
  1257. * @param int $session_id
  1258. * @param bool $get_count
  1259. *
  1260. * @return array with the results
  1261. */
  1262. public static function get_all_exercise_results_by_course(
  1263. $courseId,
  1264. $session_id = 0,
  1265. $get_count = true
  1266. ) {
  1267. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1268. $courseId = (int) $courseId;
  1269. $session_id = (int) $session_id;
  1270. $select = '*';
  1271. if ($get_count) {
  1272. $select = 'count(*) as count';
  1273. }
  1274. $sql = "SELECT $select FROM $table_track_exercises
  1275. WHERE status = '' AND
  1276. c_id = $courseId AND
  1277. session_id = $session_id AND
  1278. orig_lp_id = 0 AND
  1279. orig_lp_item_id = 0
  1280. ORDER BY exe_id";
  1281. $res = Database::query($sql);
  1282. if ($get_count) {
  1283. $row = Database::fetch_array($res, 'ASSOC');
  1284. return $row['count'];
  1285. } else {
  1286. $list = [];
  1287. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1288. $list[$row['exe_id']] = $row;
  1289. }
  1290. return $list;
  1291. }
  1292. }
  1293. /**
  1294. * Gets all exercise results (NO Exercises in LPs) from a given exercise id, course, session.
  1295. *
  1296. * @param int $user_id
  1297. * @param int $courseId
  1298. * @param int $session_id
  1299. *
  1300. * @return array with the results
  1301. */
  1302. public static function get_all_exercise_results_by_user(
  1303. $user_id,
  1304. $courseId,
  1305. $session_id = 0
  1306. ) {
  1307. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1308. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1309. $courseId = (int) $courseId;
  1310. $session_id = (int) $session_id;
  1311. $user_id = (int) $user_id;
  1312. $sql = "SELECT * FROM $table_track_exercises
  1313. WHERE
  1314. status = '' AND
  1315. exe_user_id = $user_id AND
  1316. c_id = $courseId AND
  1317. session_id = $session_id AND
  1318. orig_lp_id = 0 AND
  1319. orig_lp_item_id = 0
  1320. ORDER by exe_id";
  1321. $res = Database::query($sql);
  1322. $list = [];
  1323. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1324. $list[$row['exe_id']] = $row;
  1325. $sql = "SELECT * FROM $table_track_attempt
  1326. WHERE exe_id = {$row['exe_id']}";
  1327. $res_question = Database::query($sql);
  1328. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1329. $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q;
  1330. }
  1331. }
  1332. return $list;
  1333. }
  1334. /**
  1335. * Gets exercise results (NO Exercises in LPs) from a given exercise id, course, session.
  1336. *
  1337. * @param int $exe_id attempt id
  1338. * @param string $status
  1339. *
  1340. * @return array with the results
  1341. */
  1342. public static function get_exercise_results_by_attempt($exe_id, $status = null)
  1343. {
  1344. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1345. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1346. $table_track_attempt_recording = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  1347. $exe_id = (int) $exe_id;
  1348. $status = Database::escape_string($status);
  1349. $sql = "SELECT * FROM $table_track_exercises
  1350. WHERE status = '$status' AND exe_id = $exe_id";
  1351. $res = Database::query($sql);
  1352. $list = [];
  1353. if (Database::num_rows($res)) {
  1354. $row = Database::fetch_array($res, 'ASSOC');
  1355. //Checking if this attempt was revised by a teacher
  1356. $sql_revised = "SELECT exe_id FROM $table_track_attempt_recording
  1357. WHERE author != '' AND exe_id = $exe_id
  1358. LIMIT 1";
  1359. $res_revised = Database::query($sql_revised);
  1360. $row['attempt_revised'] = 0;
  1361. if (Database::num_rows($res_revised) > 0) {
  1362. $row['attempt_revised'] = 1;
  1363. }
  1364. $list[$exe_id] = $row;
  1365. $sql = "SELECT * FROM $table_track_attempt
  1366. WHERE exe_id = $exe_id
  1367. ORDER BY tms ASC";
  1368. $res_question = Database::query($sql);
  1369. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1370. $list[$exe_id]['question_list'][$row_q['question_id']] = $row_q;
  1371. }
  1372. }
  1373. return $list;
  1374. }
  1375. /**
  1376. * Gets exercise results (NO Exercises in LPs) from a given user, exercise id, course, session, lp_id, lp_item_id.
  1377. *
  1378. * @param int user id
  1379. * @param int exercise id
  1380. * @param string course code
  1381. * @param int session id
  1382. * @param int lp id
  1383. * @param int lp item id
  1384. * @param string order asc or desc
  1385. *
  1386. * @return array with the results
  1387. */
  1388. public static function getExerciseResultsByUser(
  1389. $user_id,
  1390. $exercise_id,
  1391. $courseId,
  1392. $session_id = 0,
  1393. $lp_id = 0,
  1394. $lp_item_id = 0,
  1395. $order = null
  1396. ) {
  1397. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1398. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1399. $table_track_attempt_recording = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  1400. $courseId = (int) $courseId;
  1401. $exercise_id = (int) $exercise_id;
  1402. $session_id = (int) $session_id;
  1403. $user_id = (int) $user_id;
  1404. $lp_id = (int) $lp_id;
  1405. $lp_item_id = (int) $lp_item_id;
  1406. if (!in_array(strtolower($order), ['asc', 'desc'])) {
  1407. $order = 'asc';
  1408. }
  1409. $sql = "SELECT * FROM $table_track_exercises
  1410. WHERE
  1411. status = '' AND
  1412. exe_user_id = $user_id AND
  1413. c_id = $courseId AND
  1414. exe_exo_id = $exercise_id AND
  1415. session_id = $session_id AND
  1416. orig_lp_id = $lp_id AND
  1417. orig_lp_item_id = $lp_item_id
  1418. ORDER by exe_id $order ";
  1419. $res = Database::query($sql);
  1420. $list = [];
  1421. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1422. // Checking if this attempt was revised by a teacher
  1423. $exeId = $row['exe_id'];
  1424. $sql = "SELECT exe_id FROM $table_track_attempt_recording
  1425. WHERE author != '' AND exe_id = $exeId
  1426. LIMIT 1";
  1427. $res_revised = Database::query($sql);
  1428. $row['attempt_revised'] = 0;
  1429. if (Database::num_rows($res_revised) > 0) {
  1430. $row['attempt_revised'] = 1;
  1431. }
  1432. $list[$row['exe_id']] = $row;
  1433. $sql = "SELECT * FROM $table_track_attempt
  1434. WHERE exe_id = $exeId";
  1435. $res_question = Database::query($sql);
  1436. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1437. $list[$row['exe_id']]['question_list'][$row_q['question_id']][] = $row_q;
  1438. }
  1439. }
  1440. return $list;
  1441. }
  1442. /**
  1443. * Count exercise attempts (NO Exercises in LPs ) from a given exercise id, course, session.
  1444. *
  1445. * @param int $user_id
  1446. * @param int $exercise_id
  1447. * @param int $courseId
  1448. * @param int $session_id
  1449. *
  1450. * @return array with the results
  1451. */
  1452. public static function count_exercise_attempts_by_user(
  1453. $user_id,
  1454. $exercise_id,
  1455. $courseId,
  1456. $session_id = 0
  1457. ) {
  1458. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1459. $courseId = (int) $courseId;
  1460. $exercise_id = (int) $exercise_id;
  1461. $session_id = (int) $session_id;
  1462. $user_id = (int) $user_id;
  1463. $sql = "SELECT count(*) as count
  1464. FROM $table
  1465. WHERE status = '' AND
  1466. exe_user_id = $user_id AND
  1467. c_id = $courseId AND
  1468. exe_exo_id = $exercise_id AND
  1469. session_id = $session_id AND
  1470. orig_lp_id =0 AND
  1471. orig_lp_item_id = 0
  1472. ORDER BY exe_id";
  1473. $res = Database::query($sql);
  1474. $result = 0;
  1475. if (Database::num_rows($res) > 0) {
  1476. $row = Database::fetch_array($res, 'ASSOC');
  1477. $result = $row['count'];
  1478. }
  1479. return $result;
  1480. }
  1481. /**
  1482. * Gets all exercise BEST results attempts (NO Exercises in LPs)
  1483. * from a given exercise id, course, session per user.
  1484. *
  1485. * @param int $exercise_id
  1486. * @param int $courseId
  1487. * @param int $session_id
  1488. * @param int $userId
  1489. *
  1490. * @return array with the results
  1491. *
  1492. * @todo rename this function
  1493. */
  1494. public static function get_best_exercise_results_by_user(
  1495. $exercise_id,
  1496. $courseId,
  1497. $session_id = 0,
  1498. $userId = 0
  1499. ) {
  1500. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1501. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1502. $courseId = (int) $courseId;
  1503. $exercise_id = (int) $exercise_id;
  1504. $session_id = (int) $session_id;
  1505. $sql = "SELECT * FROM $table_track_exercises
  1506. WHERE
  1507. status = '' AND
  1508. c_id = $courseId AND
  1509. exe_exo_id = $exercise_id AND
  1510. session_id = $session_id AND
  1511. orig_lp_id = 0 AND
  1512. orig_lp_item_id = 0";
  1513. if (!empty($userId)) {
  1514. $userId = (int) $userId;
  1515. $sql .= " AND exe_user_id = $userId ";
  1516. }
  1517. $sql .= ' ORDER BY exe_id';
  1518. $res = Database::query($sql);
  1519. $list = [];
  1520. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1521. $list[$row['exe_id']] = $row;
  1522. $exeId = $row['exe_id'];
  1523. $sql = "SELECT * FROM $table_track_attempt
  1524. WHERE exe_id = $exeId";
  1525. $res_question = Database::query($sql);
  1526. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1527. $list[$exeId]['question_list'][$row_q['question_id']] = $row_q;
  1528. }
  1529. }
  1530. // Getting the best results of every student
  1531. $best_score_return = [];
  1532. foreach ($list as $student_result) {
  1533. $user_id = $student_result['exe_user_id'];
  1534. $current_best_score[$user_id] = $student_result['exe_result'];
  1535. if (!isset($best_score_return[$user_id]['exe_result'])) {
  1536. $best_score_return[$user_id] = $student_result;
  1537. }
  1538. if ($current_best_score[$user_id] > $best_score_return[$user_id]['exe_result']) {
  1539. $best_score_return[$user_id] = $student_result;
  1540. }
  1541. }
  1542. return $best_score_return;
  1543. }
  1544. /**
  1545. * Get the last best result from all attempts in exercises per user (out of learning paths).
  1546. *
  1547. * @param int $user_id
  1548. * @param int $exercise_id
  1549. * @param int $courseId
  1550. * @param int $session_id
  1551. *
  1552. * @return array
  1553. */
  1554. public static function get_best_attempt_exercise_results_per_user(
  1555. $user_id,
  1556. $exercise_id,
  1557. $courseId,
  1558. $session_id = 0
  1559. ) {
  1560. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1561. $courseId = (int) $courseId;
  1562. $exercise_id = (int) $exercise_id;
  1563. $session_id = (int) $session_id;
  1564. $user_id = (int) $user_id;
  1565. $sql = "SELECT * FROM $table_track_exercises
  1566. WHERE
  1567. status = '' AND
  1568. c_id = $courseId AND
  1569. exe_exo_id = $exercise_id AND
  1570. session_id = $session_id AND
  1571. exe_user_id = $user_id AND
  1572. orig_lp_id = 0 AND
  1573. orig_lp_item_id = 0
  1574. ORDER BY exe_id";
  1575. $res = Database::query($sql);
  1576. $list = [];
  1577. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1578. $list[$row['exe_id']] = $row;
  1579. }
  1580. //Getting the best results of every student
  1581. $best_score_return = [];
  1582. $best_score_return['exe_result'] = 0;
  1583. foreach ($list as $result) {
  1584. $current_best_score = $result;
  1585. if ($current_best_score['exe_result'] > $best_score_return['exe_result']) {
  1586. $best_score_return = $result;
  1587. }
  1588. }
  1589. if (!isset($best_score_return['exe_weighting'])) {
  1590. $best_score_return = [];
  1591. }
  1592. return $best_score_return;
  1593. }
  1594. /**
  1595. * @param int $exercise_id
  1596. * @param int $courseId
  1597. * @param int $session_id
  1598. *
  1599. * @return mixed
  1600. */
  1601. public static function count_exercise_result_not_validated(
  1602. $exercise_id,
  1603. $courseId,
  1604. $session_id = 0
  1605. ) {
  1606. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1607. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  1608. $courseId = (int) $courseId;
  1609. $session_id = (int) $session_id;
  1610. $exercise_id = (int) $exercise_id;
  1611. $sql = "SELECT count(e.exe_id) as count
  1612. FROM $table_track_exercises e
  1613. LEFT JOIN $table_track_attempt a
  1614. ON e.exe_id = a.exe_id
  1615. WHERE
  1616. exe_exo_id = $exercise_id AND
  1617. c_id = $courseId AND
  1618. e.session_id = $session_id AND
  1619. orig_lp_id = 0 AND
  1620. marks IS NULL AND
  1621. status = '' AND
  1622. orig_lp_item_id = 0
  1623. ORDER BY e.exe_id";
  1624. $res = Database::query($sql);
  1625. $row = Database::fetch_array($res, 'ASSOC');
  1626. return $row['count'];
  1627. }
  1628. /**
  1629. * Gets all exercise events from a Learning Path within a Course nd Session.
  1630. *
  1631. * @param int $exercise_id
  1632. * @param int $courseId
  1633. * @param int $session_id
  1634. *
  1635. * @return array
  1636. */
  1637. public static function get_all_exercise_event_from_lp(
  1638. $exercise_id,
  1639. $courseId,
  1640. $session_id = 0
  1641. ) {
  1642. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1643. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1644. $courseId = (int) $courseId;
  1645. $exercise_id = (int) $exercise_id;
  1646. $session_id = (int) $session_id;
  1647. $sql = "SELECT * FROM $table_track_exercises
  1648. WHERE
  1649. status = '' AND
  1650. c_id = $courseId AND
  1651. exe_exo_id = $exercise_id AND
  1652. session_id = $session_id AND
  1653. orig_lp_id !=0 AND
  1654. orig_lp_item_id != 0";
  1655. $res = Database::query($sql);
  1656. $list = [];
  1657. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1658. $exeId = $row['exe_id'];
  1659. $list[$exeId] = $row;
  1660. $sql = "SELECT * FROM $table_track_attempt
  1661. WHERE exe_id = $exeId";
  1662. $res_question = Database::query($sql);
  1663. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1664. $list[$exeId]['question_list'][$row_q['question_id']] = $row_q;
  1665. }
  1666. }
  1667. return $list;
  1668. }
  1669. /**
  1670. * Get a list of all the exercises in a given learning path.
  1671. *
  1672. * @param int $lp_id
  1673. * @param int $course_id This parameter is probably deprecated as lp_id now is a global iid
  1674. *
  1675. * @return array
  1676. */
  1677. public static function get_all_exercises_from_lp($lp_id, $course_id)
  1678. {
  1679. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  1680. $course_id = (int) $course_id;
  1681. $lp_id = (int) $lp_id;
  1682. $sql = "SELECT * FROM $lp_item_table
  1683. WHERE
  1684. c_id = $course_id AND
  1685. lp_id = $lp_id AND
  1686. item_type = 'quiz'
  1687. ORDER BY parent_item_id, display_order";
  1688. $res = Database::query($sql);
  1689. $list = [];
  1690. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1691. $list[] = $row;
  1692. }
  1693. return $list;
  1694. }
  1695. /**
  1696. * This function gets the comments of an exercise.
  1697. *
  1698. * @param int $exe_id
  1699. * @param int $question_id
  1700. *
  1701. * @return string the comment
  1702. */
  1703. public static function get_comments($exe_id, $question_id)
  1704. {
  1705. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1706. $exe_id = (int) $exe_id;
  1707. $question_id = (int) $question_id;
  1708. $sql = "SELECT teacher_comment
  1709. FROM $table
  1710. WHERE
  1711. exe_id = $exe_id AND
  1712. question_id = $question_id
  1713. ORDER by question_id";
  1714. $sqlres = Database::query($sql);
  1715. $comm = strval(Database::result($sqlres, 0, 'teacher_comment'));
  1716. $comm = trim($comm);
  1717. return $comm;
  1718. }
  1719. /**
  1720. * @param int $exeId
  1721. *
  1722. * @return array
  1723. */
  1724. public static function getAllExerciseEventByExeId($exeId)
  1725. {
  1726. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1727. $exeId = (int) $exeId;
  1728. $sql = "SELECT * FROM $table
  1729. WHERE exe_id = $exeId
  1730. ORDER BY position";
  1731. $res_question = Database::query($sql);
  1732. $list = [];
  1733. if (Database::num_rows($res_question)) {
  1734. while ($row = Database::fetch_array($res_question, 'ASSOC')) {
  1735. $list[$row['question_id']][] = $row;
  1736. }
  1737. }
  1738. return $list;
  1739. }
  1740. /**
  1741. * @param int $exeId
  1742. * @param int $user_id
  1743. * @param int $courseId
  1744. * @param int $session_id
  1745. * @param int $question_id
  1746. */
  1747. public static function delete_attempt(
  1748. $exeId,
  1749. $user_id,
  1750. $courseId,
  1751. $session_id,
  1752. $question_id
  1753. ) {
  1754. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1755. $exeId = (int) $exeId;
  1756. $user_id = (int) $user_id;
  1757. $courseId = (int) $courseId;
  1758. $session_id = (int) $session_id;
  1759. $question_id = (int) $question_id;
  1760. $sql = "DELETE FROM $table
  1761. WHERE
  1762. exe_id = $exeId AND
  1763. user_id = $user_id AND
  1764. c_id = $courseId AND
  1765. session_id = $session_id AND
  1766. question_id = $question_id ";
  1767. Database::query($sql);
  1768. self::addEvent(
  1769. LOG_QUESTION_RESULT_DELETE,
  1770. LOG_EXERCISE_ATTEMPT_QUESTION_ID,
  1771. $exeId.'-'.$question_id,
  1772. null,
  1773. null,
  1774. $courseId,
  1775. $session_id
  1776. );
  1777. }
  1778. /**
  1779. * @param $exeId
  1780. * @param $user_id
  1781. * @param int $courseId
  1782. * @param $question_id
  1783. * @param int $sessionId
  1784. */
  1785. public static function delete_attempt_hotspot(
  1786. $exeId,
  1787. $user_id,
  1788. $courseId,
  1789. $question_id,
  1790. $sessionId = null
  1791. ) {
  1792. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  1793. $exeId = (int) $exeId;
  1794. $user_id = (int) $user_id;
  1795. $courseId = (int) $courseId;
  1796. $question_id = (int) $question_id;
  1797. if (!isset($sessionId)) {
  1798. $sessionId = api_get_session_id();
  1799. }
  1800. $sql = "DELETE FROM $table
  1801. WHERE
  1802. hotspot_exe_id = $exeId AND
  1803. hotspot_user_id = $user_id AND
  1804. c_id = $courseId AND
  1805. hotspot_question_id = $question_id ";
  1806. Database::query($sql);
  1807. self::addEvent(
  1808. LOG_QUESTION_RESULT_DELETE,
  1809. LOG_EXERCISE_ATTEMPT_QUESTION_ID,
  1810. $exeId.'-'.$question_id,
  1811. null,
  1812. null,
  1813. $courseId,
  1814. $sessionId
  1815. );
  1816. }
  1817. /**
  1818. * Registers in track_e_course_access when user logs in for the first time to a course.
  1819. *
  1820. * @param int $courseId ID of the course
  1821. * @param int $user_id ID of the user
  1822. * @param int $sessionId ID of the session (if any)
  1823. *
  1824. * @return bool
  1825. */
  1826. public static function eventCourseLogin($courseId, $user_id, $sessionId)
  1827. {
  1828. if (Session::read('login_as')) {
  1829. return false;
  1830. }
  1831. $sessionId = (int) $sessionId;
  1832. if (self::isSessionLogNeedToBeSave($sessionId) === false) {
  1833. return false;
  1834. }
  1835. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1836. $loginDate = $logoutDate = api_get_utc_datetime();
  1837. // $counter represents the number of time this record has been refreshed
  1838. $counter = 1;
  1839. $courseId = (int) $courseId;
  1840. $user_id = (int) $user_id;
  1841. $ip = Database::escape_string(api_get_real_ip());
  1842. $sql = "INSERT INTO $table(c_id, user_ip, user_id, login_course_date, logout_course_date, counter, session_id)
  1843. VALUES($courseId, '$ip', $user_id, '$loginDate', '$logoutDate', $counter, $sessionId)";
  1844. $courseAccessId = Database::query($sql);
  1845. if ($courseAccessId) {
  1846. // Course catalog stats modifications see #4191
  1847. CourseManager::update_course_ranking(
  1848. null,
  1849. null,
  1850. null,
  1851. null,
  1852. true,
  1853. false
  1854. );
  1855. return true;
  1856. }
  1857. }
  1858. /**
  1859. * Updates the user - course - session every X minutes
  1860. * In order to avoid.
  1861. *
  1862. * @param int $courseId
  1863. * @param int $userId
  1864. * @param int $sessionId
  1865. * @param int $minutes
  1866. *
  1867. * @return bool
  1868. */
  1869. public static function eventCourseLoginUpdate(
  1870. $courseId,
  1871. $userId,
  1872. $sessionId,
  1873. $minutes = 5
  1874. ) {
  1875. if (Session::read('login_as')) {
  1876. return false;
  1877. }
  1878. if (empty($courseId) || empty($userId)) {
  1879. return false;
  1880. }
  1881. $sessionId = (int) $sessionId;
  1882. if (self::isSessionLogNeedToBeSave($sessionId) === false) {
  1883. return false;
  1884. }
  1885. $courseId = (int) $courseId;
  1886. $userId = (int) $userId;
  1887. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1888. $sql = "SELECT course_access_id, logout_course_date
  1889. FROM $table
  1890. WHERE
  1891. c_id = $courseId AND
  1892. session_id = $sessionId AND
  1893. user_id = $userId
  1894. ORDER BY login_course_date DESC
  1895. LIMIT 1";
  1896. $result = Database::query($sql);
  1897. // Save every 5 minutes by default
  1898. $seconds = $minutes * 60;
  1899. $maxSeconds = 3600; // Only update if max diff is one hour
  1900. if (Database::num_rows($result)) {
  1901. $row = Database::fetch_array($result);
  1902. $id = $row['course_access_id'];
  1903. $logout = $row['logout_course_date'];
  1904. $now = time();
  1905. $logout = api_strtotime($logout, 'UTC');
  1906. if ($now - $logout > $seconds &&
  1907. $now - $logout < $maxSeconds
  1908. ) {
  1909. $now = api_get_utc_datetime();
  1910. $sql = "UPDATE $table SET
  1911. logout_course_date = '$now',
  1912. counter = counter + 1
  1913. WHERE course_access_id = $id";
  1914. Database::query($sql);
  1915. }
  1916. return true;
  1917. }
  1918. return false;
  1919. }
  1920. /**
  1921. * Register the logout of the course (usually when logging out of the platform)
  1922. * from the track_e_course_access table.
  1923. *
  1924. * @param array $logoutInfo Information stored by local.inc.php
  1925. * before new context ['uid'=> x, 'cid'=>y, 'sid'=>z]
  1926. *
  1927. * @return bool
  1928. */
  1929. public static function courseLogout($logoutInfo)
  1930. {
  1931. if (Session::read('login_as')) {
  1932. return false;
  1933. }
  1934. if (empty($logoutInfo['uid']) || empty($logoutInfo['cid'])) {
  1935. return false;
  1936. }
  1937. $sessionLifetime = api_get_configuration_value('session_lifetime');
  1938. /*
  1939. * When $_configuration['session_lifetime'] is larger than ~100 hours
  1940. * (in order to let users take exercises with no problems)
  1941. * the function Tracking::get_time_spent_on_the_course() returns larger values (200h) due the condition:
  1942. * login_course_date > now() - INTERVAL $session_lifetime SECOND
  1943. */
  1944. if (empty($sessionLifetime) || $sessionLifetime > 86400) {
  1945. $sessionLifetime = 3600; // 1 hour
  1946. }
  1947. if (!empty($logoutInfo) && !empty($logoutInfo['cid'])) {
  1948. $sessionId = 0;
  1949. if (!empty($logoutInfo['sid'])) {
  1950. $sessionId = (int) $logoutInfo['sid'];
  1951. }
  1952. if (self::isSessionLogNeedToBeSave($sessionId) === false) {
  1953. return false;
  1954. }
  1955. $tableCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1956. $userId = (int) $logoutInfo['uid'];
  1957. $courseId = (int) $logoutInfo['cid'];
  1958. $currentDate = api_get_utc_datetime();
  1959. // UTC time
  1960. $diff = time() - $sessionLifetime;
  1961. $time = api_get_utc_datetime($diff);
  1962. $sql = "SELECT course_access_id, logout_course_date
  1963. FROM $tableCourseAccess
  1964. WHERE
  1965. user_id = $userId AND
  1966. c_id = $courseId AND
  1967. session_id = $sessionId AND
  1968. login_course_date > '$time'
  1969. ORDER BY login_course_date DESC
  1970. LIMIT 1";
  1971. $result = Database::query($sql);
  1972. $insert = false;
  1973. if (Database::num_rows($result) > 0) {
  1974. $row = Database::fetch_array($result, 'ASSOC');
  1975. $courseAccessId = $row['course_access_id'];
  1976. $sql = "UPDATE $tableCourseAccess SET
  1977. logout_course_date = '$currentDate',
  1978. counter = counter + 1
  1979. WHERE course_access_id = $courseAccessId";
  1980. Database::query($sql);
  1981. } else {
  1982. $insert = true;
  1983. }
  1984. if ($insert) {
  1985. $ip = Database::escape_string(api_get_real_ip());
  1986. $sql = "INSERT INTO $tableCourseAccess (c_id, user_ip, user_id, login_course_date, logout_course_date, counter, session_id)
  1987. VALUES ($courseId, '$ip', $userId, '$currentDate', '$currentDate', 1, $sessionId)";
  1988. Database::query($sql);
  1989. }
  1990. return true;
  1991. }
  1992. }
  1993. /**
  1994. * Register a "fake" time spent on the platform, for example to match the
  1995. * estimated time he took to author an assignment/work, see configuration
  1996. * setting considered_working_time.
  1997. * This assumes there is already some connection of the student to the
  1998. * course, otherwise he wouldn't be able to upload an assignment.
  1999. * This works by creating a new record, copy of the current one, then
  2000. * updating the current one to be just the considered_working_time and
  2001. * end at the same second as the user connected to the course.
  2002. *
  2003. * @param int $courseId The course in which to add the time
  2004. * @param int $userId The user for whom to add the time
  2005. * @param int $sessionId The session in which to add the time (if any)
  2006. * @param string $virtualTime The amount of time to be added,
  2007. * in a hh:mm:ss format. If int, we consider it is expressed in hours.
  2008. *
  2009. * @return true on successful insertion, false otherwise
  2010. */
  2011. public static function eventAddVirtualCourseTime(
  2012. $courseId,
  2013. $userId,
  2014. $sessionId,
  2015. $virtualTime = ''
  2016. ) {
  2017. $courseId = (int) $courseId;
  2018. $userId = (int) $userId;
  2019. $sessionId = (int) $sessionId;
  2020. $logoutDate = api_get_utc_datetime();
  2021. $loginDate = ChamiloApi::addOrSubTimeToDateTime(
  2022. $virtualTime,
  2023. $logoutDate,
  2024. false
  2025. );
  2026. $params = [
  2027. 'login_course_date' => $loginDate,
  2028. 'logout_course_date' => $logoutDate,
  2029. 'session_id' => $sessionId,
  2030. 'user_id' => $userId,
  2031. 'counter' => 0,
  2032. 'c_id' => $courseId,
  2033. 'user_ip' => api_get_real_ip(),
  2034. ];
  2035. $courseTrackingTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  2036. Database::insert($courseTrackingTable, $params);
  2037. return true;
  2038. }
  2039. /**
  2040. * Removes a "fake" time spent on the platform, for example to match the
  2041. * estimated time he took to author an assignment/work, see configuration
  2042. * setting considered_working_time.
  2043. * This method should be called when something that generated a fake
  2044. * time record is removed. Given the database link is weak (no real
  2045. * relationship kept between the deleted item and this record), this
  2046. * method just looks for the latest record that has the same time as the
  2047. * item's fake time, is in the past and in this course+session. If such a
  2048. * record cannot be found, it doesn't do anything.
  2049. * The IP address is not considered a useful filter here.
  2050. *
  2051. * @param int $courseId The course in which to add the time
  2052. * @param int $userId The user for whom to add the time
  2053. * @param int $sessionId The session in which to add the time (if any)
  2054. * @param string $virtualTime The amount of time to be added, in a hh:mm:ss format. If int, we consider it is expressed in hours.
  2055. *
  2056. * @return true on successful removal, false otherwise
  2057. */
  2058. public static function eventRemoveVirtualCourseTime(
  2059. $courseId,
  2060. $userId,
  2061. $sessionId = 0,
  2062. $virtualTime = ''
  2063. ) {
  2064. if (empty($virtualTime)) {
  2065. return false;
  2066. }
  2067. $courseTrackingTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  2068. $courseId = (int) $courseId;
  2069. $userId = (int) $userId;
  2070. $sessionId = (int) $sessionId;
  2071. // Change $virtualTime format from hh:mm:ss to hhmmss which is the
  2072. // format returned by SQL for a subtraction of two datetime values
  2073. // @todo make sure this is portable between DBMSes
  2074. if (preg_match('/:/', $virtualTime)) {
  2075. list($h, $m, $s) = preg_split('/:/', $virtualTime);
  2076. $virtualTime = $h * 3600 + $m * 60 + $s;
  2077. } else {
  2078. $virtualTime *= 3600;
  2079. }
  2080. // Get the current latest course connection register. We need that
  2081. // record to re-use the data and create a new record.
  2082. $sql = "SELECT course_access_id
  2083. FROM $courseTrackingTable
  2084. WHERE
  2085. user_id = $userId AND
  2086. c_id = $courseId AND
  2087. session_id = $sessionId AND
  2088. counter = 0 AND
  2089. (UNIX_TIMESTAMP(logout_course_date) - UNIX_TIMESTAMP(login_course_date)) = '$virtualTime'
  2090. ORDER BY login_course_date DESC LIMIT 0,1";
  2091. $result = Database::query($sql);
  2092. // Ignore if we didn't find any course connection record in the last
  2093. // hour. In this case it wouldn't be right to add a "fake" time record.
  2094. if (Database::num_rows($result) > 0) {
  2095. // Found the latest connection
  2096. $row = Database::fetch_row($result);
  2097. $courseAccessId = $row[0];
  2098. $sql = "DELETE FROM $courseTrackingTable
  2099. WHERE course_access_id = $courseAccessId";
  2100. $result = Database::query($sql);
  2101. return $result;
  2102. }
  2103. return false;
  2104. }
  2105. /**
  2106. * For the sake of genericity, this function is a switch.
  2107. * It's called by EventsDispatcher and fires the good function
  2108. * with the good require_once.
  2109. *
  2110. * @deprecated
  2111. *
  2112. * @param string $event_name
  2113. * @param array $params
  2114. */
  2115. public static function event_send_mail($event_name, $params)
  2116. {
  2117. EventsMail::send_mail($event_name, $params);
  2118. }
  2119. /**
  2120. * Filter EventEmailTemplate Filters see the main/inc/conf/events.conf.dist.php.
  2121. */
  2122. /**
  2123. * Basic template event message filter (to be used by other filters as default).
  2124. *
  2125. * @deprecated
  2126. *
  2127. * @param array $values (passing by reference) *
  2128. *
  2129. * @return bool True if everything is OK, false otherwise
  2130. */
  2131. public function event_send_mail_filter_func(&$values)
  2132. {
  2133. return true;
  2134. }
  2135. /**
  2136. * user_registration - send_mail filter.
  2137. *
  2138. * @deprecated
  2139. *
  2140. * @param array $values (passing by reference)
  2141. *
  2142. * @return bool True if everything is OK, false otherwise
  2143. */
  2144. public function user_registration_event_send_mail_filter_func(&$values)
  2145. {
  2146. $res = self::event_send_mail_filter_func($values);
  2147. // proper logic for this filter
  2148. return $res;
  2149. }
  2150. /**
  2151. * portal_homepage_edited - send_mail filter.
  2152. *
  2153. * @deprecated
  2154. *
  2155. * @param array $values (passing by reference)
  2156. *
  2157. * @return bool True if everything is OK, false otherwise
  2158. */
  2159. public function portal_homepage_edited_event_send_mail_filter_func(&$values)
  2160. {
  2161. $res = self::event_send_mail_filter_func($values);
  2162. // proper logic for this filter
  2163. return $res;
  2164. }
  2165. /**
  2166. * Register the logout of the course (usually when logging out of the platform)
  2167. * from the track_e_access_complete table.
  2168. *
  2169. * @param array $logInfo Information stored by local.inc.php
  2170. *
  2171. * @return bool
  2172. */
  2173. public static function registerLog($logInfo)
  2174. {
  2175. $sessionId = api_get_session_id();
  2176. $courseId = api_get_course_int_id();
  2177. if (!Tracking::minimumTimeAvailable($sessionId, $courseId)) {
  2178. return false;
  2179. }
  2180. if (self::isSessionLogNeedToBeSave($sessionId) === false) {
  2181. return false;
  2182. }
  2183. $loginAs = (int) Session::read('login_as') === true;
  2184. $logInfo['user_id'] = api_get_user_id();
  2185. $logInfo['date_reg'] = api_get_utc_datetime();
  2186. $logInfo['tool'] = !empty($logInfo['tool']) ? $logInfo['tool'] : '';
  2187. $logInfo['tool_id'] = !empty($logInfo['tool_id']) ? (int) $logInfo['tool_id'] : 0;
  2188. $logInfo['tool_id_detail'] = !empty($logInfo['tool_id_detail']) ? (int) $logInfo['tool_id_detail'] : 0;
  2189. $logInfo['action'] = !empty($logInfo['action']) ? $logInfo['action'] : '';
  2190. $logInfo['action_details'] = !empty($logInfo['action_details']) ? $logInfo['action_details'] : '';
  2191. $logInfo['ip_user'] = api_get_real_ip();
  2192. $logInfo['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
  2193. $logInfo['session_id'] = $sessionId;
  2194. $logInfo['c_id'] = $courseId;
  2195. $logInfo['ch_sid'] = session_id();
  2196. $logInfo['login_as'] = $loginAs;
  2197. $logInfo['info'] = !empty($logInfo['info']) ? $logInfo['info'] : '';
  2198. $logInfo['url'] = $_SERVER['REQUEST_URI'];
  2199. $logInfo['current_id'] = Session::read('last_id', 0);
  2200. $id = Database::insert('track_e_access_complete', $logInfo);
  2201. if ($id && empty($logInfo['current_id'])) {
  2202. Session::write('last_id', $id);
  2203. }
  2204. return true;
  2205. }
  2206. }