events.lib.php 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  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::subscribe_user($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. public static function delete_student_lp_events(
  1035. $user_id,
  1036. $lp_id,
  1037. $course,
  1038. $session_id
  1039. ) {
  1040. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  1041. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  1042. $lpInteraction = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  1043. $lpObjective = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  1044. $course_id = $course['real_id'];
  1045. if (empty($course_id)) {
  1046. $course_id = api_get_course_int_id();
  1047. }
  1048. $track_e_exercises = Database::get_main_table(
  1049. TABLE_STATISTIC_TRACK_E_EXERCISES
  1050. );
  1051. $track_attempts = Database::get_main_table(
  1052. TABLE_STATISTIC_TRACK_E_ATTEMPT
  1053. );
  1054. $recording_table = Database::get_main_table(
  1055. TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING
  1056. );
  1057. $user_id = (int) $user_id;
  1058. $lp_id = (int) $lp_id;
  1059. $session_id = (int) $session_id;
  1060. //Make sure we have the exact lp_view_id
  1061. $sql = "SELECT id FROM $lp_view_table
  1062. WHERE
  1063. c_id = $course_id AND
  1064. user_id = $user_id AND
  1065. lp_id = $lp_id AND
  1066. session_id = $session_id";
  1067. $result = Database::query($sql);
  1068. if (Database::num_rows($result)) {
  1069. $view = Database::fetch_array($result, 'ASSOC');
  1070. $lp_view_id = $view['id'];
  1071. $sql = "DELETE FROM $lp_item_view_table
  1072. WHERE c_id = $course_id AND lp_view_id = $lp_view_id";
  1073. Database::query($sql);
  1074. $sql = "DELETE FROM $lpInteraction
  1075. WHERE c_id = $course_id AND lp_iv_id = $lp_view_id";
  1076. Database::query($sql);
  1077. $sql = "DELETE FROM $lpObjective
  1078. WHERE c_id = $course_id AND lp_iv_id = $lp_view_id";
  1079. Database::query($sql);
  1080. }
  1081. $sql = "DELETE FROM $lp_view_table
  1082. WHERE
  1083. c_id = $course_id AND
  1084. user_id = $user_id AND
  1085. lp_id= $lp_id AND
  1086. session_id = $session_id
  1087. ";
  1088. Database::query($sql);
  1089. $sql = "SELECT exe_id FROM $track_e_exercises
  1090. WHERE
  1091. exe_user_id = $user_id AND
  1092. session_id = $session_id AND
  1093. c_id = $course_id AND
  1094. orig_lp_id = $lp_id";
  1095. $result = Database::query($sql);
  1096. $exe_list = [];
  1097. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1098. $exe_list[] = $row['exe_id'];
  1099. }
  1100. if (!empty($exe_list) && is_array($exe_list) && count($exe_list) > 0) {
  1101. $exeListString = implode(',', $exe_list);
  1102. $sql = "DELETE FROM $track_e_exercises
  1103. WHERE exe_id IN ($exeListString)";
  1104. Database::query($sql);
  1105. $sql = "DELETE FROM $track_attempts
  1106. WHERE exe_id IN ($exeListString)";
  1107. Database::query($sql);
  1108. $sql = "DELETE FROM $recording_table
  1109. WHERE exe_id IN ($exeListString)";
  1110. Database::query($sql);
  1111. }
  1112. self::addEvent(
  1113. LOG_LP_ATTEMPT_DELETE,
  1114. LOG_LP_ID,
  1115. $lp_id,
  1116. null,
  1117. null,
  1118. $course_id,
  1119. $session_id
  1120. );
  1121. }
  1122. /**
  1123. * Delete all exercise attempts (included in LP or not).
  1124. *
  1125. * @param int user id
  1126. * @param int exercise id
  1127. * @param int $course_id
  1128. * @param int session id
  1129. */
  1130. public static function delete_all_incomplete_attempts(
  1131. $user_id,
  1132. $exercise_id,
  1133. $course_id,
  1134. $session_id = 0
  1135. ) {
  1136. $track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1137. $user_id = (int) $user_id;
  1138. $exercise_id = (int) $exercise_id;
  1139. $course_id = (int) $course_id;
  1140. $session_id = (int) $session_id;
  1141. if (!empty($user_id) && !empty($exercise_id) && !empty($course_code)) {
  1142. $sql = "DELETE FROM $track_e_exercises
  1143. WHERE
  1144. exe_user_id = $user_id AND
  1145. exe_exo_id = $exercise_id AND
  1146. c_id = $course_id AND
  1147. session_id = $session_id AND
  1148. status = 'incomplete' ";
  1149. Database::query($sql);
  1150. self::addEvent(
  1151. LOG_EXERCISE_RESULT_DELETE,
  1152. LOG_EXERCISE_AND_USER_ID,
  1153. $exercise_id.'-'.$user_id,
  1154. null,
  1155. null,
  1156. $course_id,
  1157. $session_id
  1158. );
  1159. }
  1160. }
  1161. /**
  1162. * Gets all exercise results (NO Exercises in LPs ) from a given exercise id, course, session.
  1163. *
  1164. * @param int exercise id
  1165. * @param int $courseId
  1166. * @param int session id
  1167. *
  1168. * @return array with the results
  1169. */
  1170. public static function get_all_exercise_results(
  1171. $exercise_id,
  1172. $courseId,
  1173. $session_id = 0,
  1174. $load_question_list = true,
  1175. $user_id = null
  1176. ) {
  1177. $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1178. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1179. $courseId = (int) $courseId;
  1180. $exercise_id = (int) $exercise_id;
  1181. $session_id = (int) $session_id;
  1182. $user_condition = null;
  1183. if (!empty($user_id)) {
  1184. $user_id = (int) $user_id;
  1185. $user_condition = "AND exe_user_id = $user_id ";
  1186. }
  1187. $sql = "SELECT * FROM $TABLETRACK_EXERCICES
  1188. WHERE
  1189. status = '' AND
  1190. c_id = $courseId AND
  1191. exe_exo_id = $exercise_id AND
  1192. session_id = $session_id AND
  1193. orig_lp_id =0 AND
  1194. orig_lp_item_id = 0
  1195. $user_condition
  1196. ORDER BY exe_id";
  1197. $res = Database::query($sql);
  1198. $list = [];
  1199. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1200. $list[$row['exe_id']] = $row;
  1201. if ($load_question_list) {
  1202. $sql = "SELECT * FROM $TBL_TRACK_ATTEMPT
  1203. WHERE exe_id = {$row['exe_id']}";
  1204. $res_question = Database::query($sql);
  1205. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1206. $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q;
  1207. }
  1208. }
  1209. }
  1210. return $list;
  1211. }
  1212. /**
  1213. * Gets all exercise results (NO Exercises in LPs ) from a given exercise id, course, session.
  1214. *
  1215. * @param int $courseId
  1216. * @param int session id
  1217. * @param bool $get_count
  1218. *
  1219. * @return array with the results
  1220. */
  1221. public static function get_all_exercise_results_by_course(
  1222. $courseId,
  1223. $session_id = 0,
  1224. $get_count = true
  1225. ) {
  1226. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1227. $courseId = (int) $courseId;
  1228. $session_id = (int) $session_id;
  1229. $select = '*';
  1230. if ($get_count) {
  1231. $select = 'count(*) as count';
  1232. }
  1233. $sql = "SELECT $select FROM $table_track_exercises
  1234. WHERE status = '' AND
  1235. c_id = $courseId AND
  1236. session_id = $session_id AND
  1237. orig_lp_id = 0 AND
  1238. orig_lp_item_id = 0
  1239. ORDER BY exe_id";
  1240. $res = Database::query($sql);
  1241. if ($get_count) {
  1242. $row = Database::fetch_array($res, 'ASSOC');
  1243. return $row['count'];
  1244. } else {
  1245. $list = [];
  1246. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1247. $list[$row['exe_id']] = $row;
  1248. }
  1249. return $list;
  1250. }
  1251. }
  1252. /**
  1253. * Gets all exercise results (NO Exercises in LPs) from a given exercise id, course, session.
  1254. *
  1255. * @param int exercise id
  1256. * @param int $courseId
  1257. * @param int session id
  1258. *
  1259. * @return array with the results
  1260. */
  1261. public static function get_all_exercise_results_by_user(
  1262. $user_id,
  1263. $courseId,
  1264. $session_id = 0
  1265. ) {
  1266. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1267. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1268. $courseId = (int) $courseId;
  1269. $session_id = (int) $session_id;
  1270. $user_id = (int) $user_id;
  1271. $sql = "SELECT * FROM $table_track_exercises
  1272. WHERE
  1273. status = '' AND
  1274. exe_user_id = $user_id AND
  1275. c_id = $courseId AND
  1276. session_id = $session_id AND
  1277. orig_lp_id = 0 AND
  1278. orig_lp_item_id = 0
  1279. ORDER by exe_id";
  1280. $res = Database::query($sql);
  1281. $list = [];
  1282. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1283. $list[$row['exe_id']] = $row;
  1284. $sql = "SELECT * FROM $table_track_attempt
  1285. WHERE exe_id = {$row['exe_id']}";
  1286. $res_question = Database::query($sql);
  1287. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1288. $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q;
  1289. }
  1290. }
  1291. return $list;
  1292. }
  1293. /**
  1294. * Gets exercise results (NO Exercises in LPs) from a given exercise id, course, session.
  1295. *
  1296. * @param int $exe_id exercise id
  1297. * @param string $status
  1298. *
  1299. * @return array with the results
  1300. */
  1301. public static function get_exercise_results_by_attempt($exe_id, $status = null)
  1302. {
  1303. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1304. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1305. $table_track_attempt_recording = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  1306. $exe_id = (int) $exe_id;
  1307. $status = Database::escape_string($status);
  1308. $sql = "SELECT * FROM $table_track_exercises
  1309. WHERE status = '$status' AND exe_id = $exe_id";
  1310. $res = Database::query($sql);
  1311. $list = [];
  1312. if (Database::num_rows($res)) {
  1313. $row = Database::fetch_array($res, 'ASSOC');
  1314. //Checking if this attempt was revised by a teacher
  1315. $sql_revised = "SELECT exe_id FROM $table_track_attempt_recording
  1316. WHERE author != '' AND exe_id = $exe_id
  1317. LIMIT 1";
  1318. $res_revised = Database::query($sql_revised);
  1319. $row['attempt_revised'] = 0;
  1320. if (Database::num_rows($res_revised) > 0) {
  1321. $row['attempt_revised'] = 1;
  1322. }
  1323. $list[$exe_id] = $row;
  1324. $sql = "SELECT * FROM $table_track_attempt
  1325. WHERE exe_id = $exe_id
  1326. ORDER BY tms ASC";
  1327. $res_question = Database::query($sql);
  1328. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1329. $list[$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 user, exercise id, course, session, lp_id, lp_item_id.
  1336. *
  1337. * @param int user id
  1338. * @param int exercise id
  1339. * @param string course code
  1340. * @param int session id
  1341. * @param int lp id
  1342. * @param int lp item id
  1343. * @param string order asc or desc
  1344. *
  1345. * @return array with the results
  1346. */
  1347. public static function getExerciseResultsByUser(
  1348. $user_id,
  1349. $exercise_id,
  1350. $courseId,
  1351. $session_id = 0,
  1352. $lp_id = 0,
  1353. $lp_item_id = 0,
  1354. $order = null
  1355. ) {
  1356. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1357. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1358. $table_track_attempt_recording = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  1359. $courseId = (int) $courseId;
  1360. $exercise_id = (int) $exercise_id;
  1361. $session_id = (int) $session_id;
  1362. $user_id = (int) $user_id;
  1363. $lp_id = (int) $lp_id;
  1364. $lp_item_id = (int) $lp_item_id;
  1365. if (!in_array(strtolower($order), ['asc', 'desc'])) {
  1366. $order = 'asc';
  1367. }
  1368. $sql = "SELECT * FROM $table_track_exercises
  1369. WHERE
  1370. status = '' AND
  1371. exe_user_id = $user_id AND
  1372. c_id = $courseId AND
  1373. exe_exo_id = $exercise_id AND
  1374. session_id = $session_id AND
  1375. orig_lp_id = $lp_id AND
  1376. orig_lp_item_id = $lp_item_id
  1377. ORDER by exe_id $order ";
  1378. $res = Database::query($sql);
  1379. $list = [];
  1380. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1381. // Checking if this attempt was revised by a teacher
  1382. $exeId = $row['exe_id'];
  1383. $sql = "SELECT exe_id FROM $table_track_attempt_recording
  1384. WHERE author != '' AND exe_id = $exeId
  1385. LIMIT 1";
  1386. $res_revised = Database::query($sql);
  1387. $row['attempt_revised'] = 0;
  1388. if (Database::num_rows($res_revised) > 0) {
  1389. $row['attempt_revised'] = 1;
  1390. }
  1391. $list[$row['exe_id']] = $row;
  1392. $sql = "SELECT * FROM $table_track_attempt
  1393. WHERE exe_id = $exeId";
  1394. $res_question = Database::query($sql);
  1395. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1396. $list[$row['exe_id']]['question_list'][$row_q['question_id']][] = $row_q;
  1397. }
  1398. }
  1399. return $list;
  1400. }
  1401. /**
  1402. * Count exercise attempts (NO Exercises in LPs ) from a given exercise id, course, session.
  1403. *
  1404. * @param int $user_id
  1405. * @param int exercise id
  1406. * @param int $courseId
  1407. * @param int session id
  1408. *
  1409. * @return array with the results
  1410. */
  1411. public static function count_exercise_attempts_by_user(
  1412. $user_id,
  1413. $exercise_id,
  1414. $courseId,
  1415. $session_id = 0
  1416. ) {
  1417. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1418. $courseId = (int) $courseId;
  1419. $exercise_id = (int) $exercise_id;
  1420. $session_id = (int) $session_id;
  1421. $user_id = (int) $user_id;
  1422. $sql = "SELECT count(*) as count
  1423. FROM $table
  1424. WHERE status = '' AND
  1425. exe_user_id = $user_id AND
  1426. c_id = $courseId AND
  1427. exe_exo_id = $exercise_id AND
  1428. session_id = $session_id AND
  1429. orig_lp_id =0 AND
  1430. orig_lp_item_id = 0
  1431. ORDER BY exe_id";
  1432. $res = Database::query($sql);
  1433. $result = 0;
  1434. if (Database::num_rows($res) > 0) {
  1435. $row = Database::fetch_array($res, 'ASSOC');
  1436. $result = $row['count'];
  1437. }
  1438. return $result;
  1439. }
  1440. /**
  1441. * Gets all exercise BEST results attempts (NO Exercises in LPs)
  1442. * from a given exercise id, course, session per user.
  1443. *
  1444. * @param int $exercise_id
  1445. * @param int $courseId
  1446. * @param int $session_id
  1447. * @param int $userId
  1448. *
  1449. * @return array with the results
  1450. *
  1451. * @todo rename this function
  1452. */
  1453. public static function get_best_exercise_results_by_user(
  1454. $exercise_id,
  1455. $courseId,
  1456. $session_id = 0,
  1457. $userId = 0
  1458. ) {
  1459. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1460. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1461. $courseId = (int) $courseId;
  1462. $exercise_id = (int) $exercise_id;
  1463. $session_id = (int) $session_id;
  1464. $sql = "SELECT * FROM $table_track_exercises
  1465. WHERE
  1466. status = '' 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. if (!empty($userId)) {
  1473. $userId = (int) $userId;
  1474. $sql .= " AND exe_user_id = $userId ";
  1475. }
  1476. $sql .= " ORDER BY exe_id";
  1477. $res = Database::query($sql);
  1478. $list = [];
  1479. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1480. $list[$row['exe_id']] = $row;
  1481. $exeId = $row['exe_id'];
  1482. $sql = "SELECT * FROM $table_track_attempt
  1483. WHERE exe_id = $exeId";
  1484. $res_question = Database::query($sql);
  1485. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1486. $list[$exeId]['question_list'][$row_q['question_id']] = $row_q;
  1487. }
  1488. }
  1489. // Getting the best results of every student
  1490. $best_score_return = [];
  1491. foreach ($list as $student_result) {
  1492. $user_id = $student_result['exe_user_id'];
  1493. $current_best_score[$user_id] = $student_result['exe_result'];
  1494. //echo $current_best_score[$user_id].' - '.$best_score_return[$user_id]['exe_result'].'<br />';
  1495. if (!isset($best_score_return[$user_id]['exe_result'])) {
  1496. $best_score_return[$user_id] = $student_result;
  1497. }
  1498. if ($current_best_score[$user_id] > $best_score_return[$user_id]['exe_result']) {
  1499. $best_score_return[$user_id] = $student_result;
  1500. }
  1501. }
  1502. return $best_score_return;
  1503. }
  1504. /**
  1505. * @param int $user_id
  1506. * @param int $exercise_id
  1507. * @param int $courseId
  1508. * @param int $session_id
  1509. *
  1510. * @return array
  1511. */
  1512. public static function get_best_attempt_exercise_results_per_user(
  1513. $user_id,
  1514. $exercise_id,
  1515. $courseId,
  1516. $session_id = 0
  1517. ) {
  1518. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1519. $courseId = (int) $courseId;
  1520. $exercise_id = (int) $exercise_id;
  1521. $session_id = (int) $session_id;
  1522. $user_id = (int) $user_id;
  1523. $sql = "SELECT * FROM $table_track_exercises
  1524. WHERE
  1525. status = '' AND
  1526. c_id = $courseId AND
  1527. exe_exo_id = $exercise_id AND
  1528. session_id = $session_id AND
  1529. exe_user_id = $user_id AND
  1530. orig_lp_id = 0 AND
  1531. orig_lp_item_id = 0
  1532. ORDER BY exe_id";
  1533. $res = Database::query($sql);
  1534. $list = [];
  1535. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1536. $list[$row['exe_id']] = $row;
  1537. }
  1538. //Getting the best results of every student
  1539. $best_score_return = [];
  1540. $best_score_return['exe_result'] = 0;
  1541. foreach ($list as $result) {
  1542. $current_best_score = $result;
  1543. if ($current_best_score['exe_result'] > $best_score_return['exe_result']) {
  1544. $best_score_return = $result;
  1545. }
  1546. }
  1547. if (!isset($best_score_return['exe_weighting'])) {
  1548. $best_score_return = [];
  1549. }
  1550. return $best_score_return;
  1551. }
  1552. /**
  1553. * @param int $exercise_id
  1554. * @param int $courseId
  1555. * @param int $session_id
  1556. *
  1557. * @return mixed
  1558. */
  1559. public static function count_exercise_result_not_validated(
  1560. $exercise_id,
  1561. $courseId,
  1562. $session_id = 0
  1563. ) {
  1564. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1565. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  1566. $courseId = (int) $courseId;
  1567. $session_id = (int) $session_id;
  1568. $exercise_id = (int) $exercise_id;
  1569. $sql = "SELECT count(e.exe_id) as count
  1570. FROM $table_track_exercises e
  1571. LEFT JOIN $table_track_attempt a
  1572. ON e.exe_id = a.exe_id
  1573. WHERE
  1574. exe_exo_id = $exercise_id AND
  1575. c_id = $courseId AND
  1576. e.session_id = $session_id AND
  1577. orig_lp_id = 0 AND
  1578. marks IS NULL AND
  1579. status = '' AND
  1580. orig_lp_item_id = 0
  1581. ORDER BY e.exe_id";
  1582. $res = Database::query($sql);
  1583. $row = Database::fetch_array($res, 'ASSOC');
  1584. return $row['count'];
  1585. }
  1586. /**
  1587. * Gets all exercise BEST results attempts (NO Exercises in LPs)
  1588. * from a given exercise id, course, session per user.
  1589. *
  1590. * @param int exercise id
  1591. * @param int course id
  1592. * @param int session id
  1593. *
  1594. * @return array with the results
  1595. */
  1596. public static function get_count_exercises_attempted_by_course(
  1597. $courseId,
  1598. $session_id = 0
  1599. ) {
  1600. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1601. $courseId = (int) $courseId;
  1602. $session_id = (int) $session_id;
  1603. $sql = "SELECT DISTINCT exe_exo_id, exe_user_id
  1604. FROM $table_track_exercises
  1605. WHERE
  1606. status = '' AND
  1607. c_id = $courseId AND
  1608. session_id = $session_id AND
  1609. orig_lp_id = 0 AND
  1610. orig_lp_item_id = 0
  1611. ORDER BY exe_id";
  1612. $res = Database::query($sql);
  1613. $count = 0;
  1614. if (Database::num_rows($res) > 0) {
  1615. $count = Database::num_rows($res);
  1616. }
  1617. return $count;
  1618. }
  1619. /**
  1620. * Gets all exercise events from a Learning Path within a Course nd Session.
  1621. *
  1622. * @param int $exercise_id
  1623. * @param int $courseId
  1624. * @param int $session_id
  1625. *
  1626. * @return array
  1627. */
  1628. public static function get_all_exercise_event_from_lp(
  1629. $exercise_id,
  1630. $courseId,
  1631. $session_id = 0
  1632. ) {
  1633. $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1634. $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1635. $courseId = (int) $courseId;
  1636. $exercise_id = (int) $exercise_id;
  1637. $session_id = (int) $session_id;
  1638. $sql = "SELECT * FROM $table_track_exercises
  1639. WHERE
  1640. status = '' AND
  1641. c_id = $courseId AND
  1642. exe_exo_id = $exercise_id AND
  1643. session_id = $session_id AND
  1644. orig_lp_id !=0 AND
  1645. orig_lp_item_id != 0";
  1646. $res = Database::query($sql);
  1647. $list = [];
  1648. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1649. $exeId = $row['exe_id'];
  1650. $list[$exeId] = $row;
  1651. $sql = "SELECT * FROM $table_track_attempt
  1652. WHERE exe_id = $exeId";
  1653. $res_question = Database::query($sql);
  1654. while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
  1655. $list[$exeId]['question_list'][$row_q['question_id']] = $row_q;
  1656. }
  1657. }
  1658. return $list;
  1659. }
  1660. /**
  1661. * Get a list of all the exercises in a given learning path.
  1662. *
  1663. * @param int $lp_id
  1664. * @param int $course_id This parameter is probably deprecated as lp_id now is a global iid
  1665. *
  1666. * @return array
  1667. */
  1668. public static function get_all_exercises_from_lp($lp_id, $course_id)
  1669. {
  1670. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  1671. $course_id = (int) $course_id;
  1672. $lp_id = (int) $lp_id;
  1673. $sql = "SELECT * FROM $lp_item_table
  1674. WHERE
  1675. c_id = $course_id AND
  1676. lp_id = $lp_id AND
  1677. item_type = 'quiz'
  1678. ORDER BY parent_item_id, display_order";
  1679. $res = Database::query($sql);
  1680. $my_exercise_list = [];
  1681. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1682. $my_exercise_list[] = $row;
  1683. }
  1684. return $my_exercise_list;
  1685. }
  1686. /**
  1687. * This function gets the comments of an exercise.
  1688. *
  1689. * @param int $exe_id
  1690. * @param int $question_id
  1691. *
  1692. * @return string the comment
  1693. */
  1694. public static function get_comments($exe_id, $question_id)
  1695. {
  1696. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1697. $exe_id = (int) $exe_id;
  1698. $question_id = (int) $question_id;
  1699. $sql = "SELECT teacher_comment
  1700. FROM $table
  1701. WHERE
  1702. exe_id = $exe_id AND
  1703. question_id = $question_id
  1704. ORDER by question_id";
  1705. $sqlres = Database::query($sql);
  1706. $comm = strval(Database::result($sqlres, 0, 'teacher_comment'));
  1707. $comm = trim($comm);
  1708. return $comm;
  1709. }
  1710. /**
  1711. * @param int $exeId
  1712. *
  1713. * @return array
  1714. */
  1715. public static function getAllExerciseEventByExeId($exeId)
  1716. {
  1717. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1718. $exeId = (int) $exeId;
  1719. $sql = "SELECT * FROM $table
  1720. WHERE exe_id = $exeId
  1721. ORDER BY position";
  1722. $res_question = Database::query($sql);
  1723. $list = [];
  1724. if (Database::num_rows($res_question)) {
  1725. while ($row = Database::fetch_array($res_question, 'ASSOC')) {
  1726. $list[$row['question_id']][] = $row;
  1727. }
  1728. }
  1729. return $list;
  1730. }
  1731. /**
  1732. * @param int $exeId
  1733. * @param int $user_id
  1734. * @param int $courseId
  1735. * @param int $session_id
  1736. * @param int $question_id
  1737. */
  1738. public static function delete_attempt(
  1739. $exeId,
  1740. $user_id,
  1741. $courseId,
  1742. $session_id,
  1743. $question_id
  1744. ) {
  1745. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1746. $exeId = (int) $exeId;
  1747. $user_id = (int) $user_id;
  1748. $courseId = (int) $courseId;
  1749. $session_id = (int) $session_id;
  1750. $question_id = (int) $question_id;
  1751. $sql = "DELETE FROM $table
  1752. WHERE
  1753. exe_id = $exeId AND
  1754. user_id = $user_id AND
  1755. c_id = $courseId AND
  1756. session_id = $session_id AND
  1757. question_id = $question_id ";
  1758. Database::query($sql);
  1759. self::addEvent(
  1760. LOG_QUESTION_RESULT_DELETE,
  1761. LOG_EXERCISE_ATTEMPT_QUESTION_ID,
  1762. $exeId.'-'.$question_id,
  1763. null,
  1764. null,
  1765. $courseId,
  1766. $session_id
  1767. );
  1768. }
  1769. /**
  1770. * @param $exeId
  1771. * @param $user_id
  1772. * @param int $courseId
  1773. * @param $question_id
  1774. * @param int $sessionId
  1775. */
  1776. public static function delete_attempt_hotspot(
  1777. $exeId,
  1778. $user_id,
  1779. $courseId,
  1780. $question_id,
  1781. $sessionId = null
  1782. ) {
  1783. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  1784. $exeId = (int) $exeId;
  1785. $user_id = (int) $user_id;
  1786. $courseId = (int) $courseId;
  1787. $question_id = (int) $question_id;
  1788. if (!isset($sessionId)) {
  1789. $sessionId = api_get_session_id();
  1790. }
  1791. $sql = "DELETE FROM $table
  1792. WHERE
  1793. hotspot_exe_id = $exeId AND
  1794. hotspot_user_id = $user_id AND
  1795. c_id = $courseId AND
  1796. hotspot_question_id = $question_id ";
  1797. Database::query($sql);
  1798. self::addEvent(
  1799. LOG_QUESTION_RESULT_DELETE,
  1800. LOG_EXERCISE_ATTEMPT_QUESTION_ID,
  1801. $exeId.'-'.$question_id,
  1802. null,
  1803. null,
  1804. $courseId,
  1805. $sessionId
  1806. );
  1807. }
  1808. /**
  1809. * Registers in track_e_course_access when user logs in for the first time to a course.
  1810. *
  1811. * @param int $courseId ID of the course
  1812. * @param int $user_id ID of the user
  1813. * @param int $sessionId ID of the session (if any)
  1814. *
  1815. * @return bool
  1816. */
  1817. public static function eventCourseLogin($courseId, $user_id, $sessionId)
  1818. {
  1819. if (Session::read('login_as')) {
  1820. return false;
  1821. }
  1822. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1823. $loginDate = $logoutDate = api_get_utc_datetime();
  1824. // $counter represents the number of time this record has been refreshed
  1825. $counter = 1;
  1826. $courseId = (int) $courseId;
  1827. $user_id = (int) $user_id;
  1828. $sessionId = (int) $sessionId;
  1829. $ip = Database::escape_string(api_get_real_ip());
  1830. $sql = "INSERT INTO $table(c_id, user_ip, user_id, login_course_date, logout_course_date, counter, session_id)
  1831. VALUES($courseId, '$ip', $user_id, '$loginDate', '$logoutDate', $counter, $sessionId)";
  1832. $courseAccessId = Database::query($sql);
  1833. if ($courseAccessId) {
  1834. // Course catalog stats modifications see #4191
  1835. CourseManager::update_course_ranking(
  1836. null,
  1837. null,
  1838. null,
  1839. null,
  1840. true,
  1841. false
  1842. );
  1843. return true;
  1844. }
  1845. }
  1846. /**
  1847. * Updates the user - course - session every X minutes
  1848. * In order to avoid.
  1849. *
  1850. * @param int $courseId
  1851. * @param int $userId
  1852. * @param int $sessionId
  1853. * @param int $minutes
  1854. *
  1855. * @return bool
  1856. */
  1857. public static function eventCourseLoginUpdate(
  1858. $courseId,
  1859. $userId,
  1860. $sessionId,
  1861. $minutes = 5
  1862. ) {
  1863. if (Session::read('login_as')) {
  1864. return false;
  1865. }
  1866. if (empty($courseId) || empty($userId)) {
  1867. return false;
  1868. }
  1869. $courseId = (int) $courseId;
  1870. $userId = (int) $userId;
  1871. $sessionId = (int) $sessionId;
  1872. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1873. $sql = "SELECT course_access_id, logout_course_date
  1874. FROM $table
  1875. WHERE
  1876. c_id = $courseId AND
  1877. session_id = $sessionId AND
  1878. user_id = $userId
  1879. ORDER BY login_course_date DESC
  1880. LIMIT 1";
  1881. $result = Database::query($sql);
  1882. // Save every 5 minutes by default
  1883. $seconds = $minutes * 60;
  1884. $maxSeconds = 3600; // Only update if max diff is one hour
  1885. if (Database::num_rows($result)) {
  1886. $row = Database::fetch_array($result);
  1887. $id = $row['course_access_id'];
  1888. $logout = $row['logout_course_date'];
  1889. $now = time();
  1890. $logout = api_strtotime($logout, 'UTC');
  1891. if ($now - $logout > $seconds &&
  1892. $now - $logout < $maxSeconds
  1893. ) {
  1894. $now = api_get_utc_datetime();
  1895. $sql = "UPDATE $table SET
  1896. logout_course_date = '$now',
  1897. counter = counter + 1
  1898. WHERE course_access_id = $id";
  1899. Database::query($sql);
  1900. }
  1901. return true;
  1902. }
  1903. return false;
  1904. }
  1905. /**
  1906. * Register the logout of the course (usually when logging out of the platform)
  1907. * from the track_e_course_access table.
  1908. *
  1909. * @param array $logoutInfo Information stored by local.inc.php
  1910. * before new context ['uid'=> x, 'cid'=>y, 'sid'=>z]
  1911. *
  1912. * @return bool
  1913. */
  1914. public static function courseLogout($logoutInfo)
  1915. {
  1916. if (Session::read('login_as')) {
  1917. return false;
  1918. }
  1919. if (empty($logoutInfo['uid']) || empty($logoutInfo['cid'])) {
  1920. return false;
  1921. }
  1922. $sessionLifetime = api_get_configuration_value('session_lifetime');
  1923. /*
  1924. * When $_configuration['session_lifetime'] is larger than ~100 hours
  1925. * (in order to let users take exercises with no problems)
  1926. * the function Tracking::get_time_spent_on_the_course() returns larger values (200h) due the condition:
  1927. * login_course_date > now() - INTERVAL $session_lifetime SECOND
  1928. */
  1929. if (empty($sessionLifetime) || $sessionLifetime > 86400) {
  1930. $sessionLifetime = 3600; // 1 hour
  1931. }
  1932. if (!empty($logoutInfo) && !empty($logoutInfo['cid'])) {
  1933. $tableCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1934. $userId = (int) $logoutInfo['uid'];
  1935. $courseId = (int) $logoutInfo['cid'];
  1936. $sessionId = 0;
  1937. if (!empty($logoutInfo['sid'])) {
  1938. $sessionId = (int) $logoutInfo['sid'];
  1939. }
  1940. $currentDate = api_get_utc_datetime();
  1941. // UTC time
  1942. $diff = time() - $sessionLifetime;
  1943. $time = api_get_utc_datetime($diff);
  1944. $sql = "SELECT course_access_id, logout_course_date
  1945. FROM $tableCourseAccess
  1946. WHERE
  1947. user_id = $userId AND
  1948. c_id = $courseId AND
  1949. session_id = $sessionId AND
  1950. login_course_date > '$time'
  1951. ORDER BY login_course_date DESC
  1952. LIMIT 1";
  1953. $result = Database::query($sql);
  1954. $insert = false;
  1955. if (Database::num_rows($result) > 0) {
  1956. $row = Database::fetch_array($result, 'ASSOC');
  1957. $courseAccessId = $row['course_access_id'];
  1958. $sql = "UPDATE $tableCourseAccess SET
  1959. logout_course_date = '$currentDate',
  1960. counter = counter + 1
  1961. WHERE course_access_id = $courseAccessId";
  1962. Database::query($sql);
  1963. } else {
  1964. $insert = true;
  1965. }
  1966. if ($insert) {
  1967. $ip = Database::escape_string(api_get_real_ip());
  1968. $sql = "INSERT INTO $tableCourseAccess (c_id, user_ip, user_id, login_course_date, logout_course_date, counter, session_id)
  1969. VALUES ($courseId, '$ip', $userId, '$currentDate', '$currentDate', 1, $sessionId)";
  1970. Database::query($sql);
  1971. }
  1972. return true;
  1973. }
  1974. }
  1975. /**
  1976. * Register a "fake" time spent on the platform, for example to match the
  1977. * estimated time he took to author an assignment/work, see configuration
  1978. * setting considered_working_time.
  1979. * This assumes there is already some connection of the student to the
  1980. * course, otherwise he wouldn't be able to upload an assignment.
  1981. * This works by creating a new record, copy of the current one, then
  1982. * updating the current one to be just the considered_working_time and
  1983. * end at the same second as the user connected to the course.
  1984. *
  1985. * @param int $courseId The course in which to add the time
  1986. * @param int $userId The user for whom to add the time
  1987. * @param int $sessionId The session in which to add the time (if any)
  1988. * @param string $virtualTime The amount of time to be added,
  1989. * in a hh:mm:ss format. If int, we consider it is expressed in hours.
  1990. * @param string $ip IP address to go on record for this time record
  1991. *
  1992. * @return true on successful insertion, false otherwise
  1993. */
  1994. public static function eventAddVirtualCourseTime(
  1995. $courseId,
  1996. $userId,
  1997. $sessionId,
  1998. $virtualTime = '',
  1999. $ip = ''
  2000. ) {
  2001. $courseTrackingTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  2002. $time = $loginDate = $logoutDate = api_get_utc_datetime();
  2003. $courseId = (int) $courseId;
  2004. $userId = (int) $userId;
  2005. $sessionId = (int) $sessionId;
  2006. $ip = Database::escape_string($ip);
  2007. // Get the current latest course connection register. We need that
  2008. // record to re-use the data and create a new record.
  2009. $sql = "SELECT *
  2010. FROM $courseTrackingTable
  2011. WHERE
  2012. user_id = $userId AND
  2013. c_id = $courseId AND
  2014. session_id = $sessionId AND
  2015. login_course_date > '$time' - INTERVAL 3600 SECOND
  2016. ORDER BY login_course_date DESC
  2017. LIMIT 0,1";
  2018. $result = Database::query($sql);
  2019. // Ignore if we didn't find any course connection record in the last
  2020. // hour. In this case it wouldn't be right to add a "fake" time record.
  2021. if (Database::num_rows($result) > 0) {
  2022. // Found the latest connection
  2023. $row = Database::fetch_array($result);
  2024. $courseAccessId = $row['course_access_id'];
  2025. $courseAccessLoginDate = $row['login_course_date'];
  2026. $counter = $row['counter'];
  2027. $counter = $counter ? $counter : 0;
  2028. // Insert a new record, copy of the current one (except the logout
  2029. // date that we update to the current time)
  2030. $sql = "INSERT INTO $courseTrackingTable(
  2031. c_id,
  2032. user_ip,
  2033. user_id,
  2034. login_course_date,
  2035. logout_course_date,
  2036. counter,
  2037. session_id
  2038. ) VALUES(
  2039. $courseId,
  2040. '$ip',
  2041. $userId,
  2042. '$courseAccessLoginDate',
  2043. '$logoutDate',
  2044. $counter,
  2045. $sessionId
  2046. )";
  2047. Database::query($sql);
  2048. $loginDate = ChamiloApi::addOrSubTimeToDateTime(
  2049. $virtualTime,
  2050. $courseAccessLoginDate,
  2051. false
  2052. );
  2053. // We update the course tracking table
  2054. $sql = "UPDATE $courseTrackingTable
  2055. SET
  2056. login_course_date = '$loginDate',
  2057. logout_course_date = '$courseAccessLoginDate',
  2058. counter = 0
  2059. WHERE
  2060. course_access_id = ".intval($courseAccessId)." AND
  2061. session_id = ".$sessionId;
  2062. Database::query($sql);
  2063. return true;
  2064. }
  2065. return false;
  2066. }
  2067. /**
  2068. * Removes a "fake" time spent on the platform, for example to match the
  2069. * estimated time he took to author an assignment/work, see configuration
  2070. * setting considered_working_time.
  2071. * This method should be called when something that generated a fake
  2072. * time record is removed. Given the database link is weak (no real
  2073. * relationship kept between the deleted item and this record), this
  2074. * method just looks for the latest record that has the same time as the
  2075. * item's fake time, is in the past and in this course+session. If such a
  2076. * record cannot be found, it doesn't do anything.
  2077. * The IP address is not considered a useful filter here.
  2078. *
  2079. * @param int $courseId The course in which to add the time
  2080. * @param int $userId The user for whom to add the time
  2081. * @param int $sessionId The session in which to add the time (if any)
  2082. * @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.
  2083. *
  2084. * @return true on successful removal, false otherwise
  2085. */
  2086. public static function eventRemoveVirtualCourseTime(
  2087. $courseId,
  2088. $userId,
  2089. $sessionId = 0,
  2090. $virtualTime = ''
  2091. ) {
  2092. if (empty($virtualTime)) {
  2093. return false;
  2094. }
  2095. $courseTrackingTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  2096. $time = $loginDate = $logoutDate = api_get_utc_datetime();
  2097. $courseId = (int) $courseId;
  2098. $userId = (int) $userId;
  2099. $sessionId = (int) $sessionId;
  2100. // Change $virtualTime format from hh:mm:ss to hhmmss which is the
  2101. // format returned by SQL for a subtraction of two datetime values
  2102. // @todo make sure this is portable between DBMSes
  2103. if (preg_match('/:/', $virtualTime)) {
  2104. list($h, $m, $s) = preg_split('/:/', $virtualTime);
  2105. $virtualTime = $h * 3600 + $m * 60 + $s;
  2106. } else {
  2107. $virtualTime *= 3600;
  2108. }
  2109. // Get the current latest course connection register. We need that
  2110. // record to re-use the data and create a new record.
  2111. $sql = "SELECT course_access_id
  2112. FROM $courseTrackingTable
  2113. WHERE
  2114. user_id = $userId AND
  2115. c_id = $courseId AND
  2116. session_id = $sessionId AND
  2117. counter = 0 AND
  2118. (UNIX_TIMESTAMP(logout_course_date) - UNIX_TIMESTAMP(login_course_date)) = '$virtualTime'
  2119. ORDER BY login_course_date DESC LIMIT 0,1";
  2120. $result = Database::query($sql);
  2121. // Ignore if we didn't find any course connection record in the last
  2122. // hour. In this case it wouldn't be right to add a "fake" time record.
  2123. if (Database::num_rows($result) > 0) {
  2124. // Found the latest connection
  2125. $row = Database::fetch_row($result);
  2126. $courseAccessId = $row[0];
  2127. $sql = "DELETE FROM $courseTrackingTable
  2128. WHERE course_access_id = $courseAccessId";
  2129. $result = Database::query($sql);
  2130. return $result;
  2131. }
  2132. return false;
  2133. }
  2134. /**
  2135. * For the sake of genericity, this function is a switch.
  2136. * It's called by EventsDispatcher and fires the good function
  2137. * with the good require_once.
  2138. *
  2139. * @deprecated
  2140. *
  2141. * @param string $event_name
  2142. * @param array $params
  2143. */
  2144. public static function event_send_mail($event_name, $params)
  2145. {
  2146. EventsMail::send_mail($event_name, $params);
  2147. }
  2148. /**
  2149. * Internal function checking if the mail was already sent from that user to that user.
  2150. *
  2151. * @param string $event_name
  2152. * @param int $user_from
  2153. * @param int $user_to
  2154. *
  2155. * @return bool
  2156. */
  2157. public static function check_if_mail_already_sent(
  2158. $event_name,
  2159. $user_from,
  2160. $user_to = null
  2161. ) {
  2162. if ($user_to == null) {
  2163. $sql = 'SELECT COUNT(*) as total
  2164. FROM '.Database::get_main_table(TABLE_EVENT_SENT).'
  2165. WHERE
  2166. user_from = '.$user_from.' AND
  2167. event_type_name = "'.$event_name.'"';
  2168. } else {
  2169. $sql = 'SELECT COUNT(*) as total
  2170. FROM '.Database::get_main_table(TABLE_EVENT_SENT).'
  2171. WHERE
  2172. user_from = '.$user_from.' AND
  2173. user_to = '.$user_to.' AND
  2174. event_type_name = "'.$event_name.'"';
  2175. }
  2176. $result = Database::store_result(Database::query($sql), 'ASSOC');
  2177. return $result[0]["total"];
  2178. }
  2179. /**
  2180. * Filter EventEmailTemplate Filters see the main/inc/conf/events.conf.dist.php.
  2181. */
  2182. /**
  2183. * Basic template event message filter (to be used by other filters as default).
  2184. *
  2185. * @deprecated
  2186. *
  2187. * @param array $values (passing by reference) *
  2188. *
  2189. * @return bool True if everything is OK, false otherwise
  2190. */
  2191. public function event_send_mail_filter_func(&$values)
  2192. {
  2193. return true;
  2194. }
  2195. /**
  2196. * user_registration - send_mail filter.
  2197. *
  2198. * @deprecated
  2199. *
  2200. * @param array $values (passing by reference)
  2201. *
  2202. * @return bool True if everything is OK, false otherwise
  2203. */
  2204. public function user_registration_event_send_mail_filter_func(&$values)
  2205. {
  2206. $res = self::event_send_mail_filter_func($values);
  2207. // proper logic for this filter
  2208. return $res;
  2209. }
  2210. /**
  2211. * portal_homepage_edited - send_mail filter.
  2212. *
  2213. * @deprecated
  2214. *
  2215. * @param array $values (passing by reference)
  2216. *
  2217. * @return bool True if everything is OK, false otherwise
  2218. */
  2219. public function portal_homepage_edited_event_send_mail_filter_func(&$values)
  2220. {
  2221. $res = self::event_send_mail_filter_func($values);
  2222. // proper logic for this filter
  2223. return $res;
  2224. }
  2225. /**
  2226. * Register the logout of the course (usually when logging out of the platform)
  2227. * from the track_e_access_complete table
  2228. *
  2229. * @param array $logInfo Information stored by local.inc.php
  2230. *
  2231. * @return bool
  2232. */
  2233. public static function registerLog($logInfo)
  2234. {
  2235. if (!api_get_configuration_value('lp_minimum_time')) {
  2236. return false;
  2237. }
  2238. $loginAs = (int) (Session::read('login_as') === true);
  2239. $logInfo['user_id'] = api_get_user_id();
  2240. $logInfo['c_id'] = api_get_course_int_id();
  2241. $logInfo['session_id'] = api_get_session_id();
  2242. $logInfo['url'] = $_SERVER['REQUEST_URI'];
  2243. $logInfo['ch_sid'] = session_id();
  2244. $logInfo['ip_user'] = api_get_real_ip();
  2245. $logInfo['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
  2246. $logInfo['login_as'] = $loginAs;
  2247. $id = Database::insert('track_e_access_complete', $logInfo);
  2248. Session::write('last_id', $id);
  2249. return true;
  2250. }
  2251. }