events.lib.php 82 KB

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