events.lib.php 80 KB

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