events.lib.php 83 KB

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