exercise.class.php 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Exercise class: This class allows to instantiate an object of type Exercise
  5. * @package chamilo.exercise
  6. * @author Olivier Brouckaert
  7. * @author Julio Montoya Cleaning exercises
  8. * Modified by Hubert Borderiou #294
  9. */
  10. /**
  11. * Code
  12. */
  13. define('ALL_ON_ONE_PAGE', 1);
  14. define('ONE_PER_PAGE', 2);
  15. define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback - show score and expected answers
  16. define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
  17. define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); //NoFeedback - Show score only
  18. define('EXERCISE_MAX_NAME_SIZE', 80);
  19. $debug = false; //All exercise scripts should depend in this debug variable
  20. require_once dirname(__FILE__).'/../inc/lib/exercise_show_functions.lib.php';
  21. /**
  22. * Exercise class
  23. * @package chamilo.exercise
  24. */
  25. class Exercise {
  26. public $id;
  27. public $name;
  28. public $title;
  29. public $exercise;
  30. public $description;
  31. public $sound;
  32. public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
  33. public $random;
  34. public $random_answers;
  35. public $active;
  36. public $timeLimit;
  37. public $attempts;
  38. public $feedback_type;
  39. public $end_time;
  40. public $start_time;
  41. public $questionList; // array with the list of this exercise's questions
  42. public $results_disabled;
  43. public $expired_time;
  44. public $course;
  45. public $course_id;
  46. public $propagate_neg;
  47. public $review_answers;
  48. public $randomByCat;
  49. public $text_when_finished;
  50. public $display_category_name;
  51. public $pass_percentage;
  52. public $edit_exercise_in_lp = false;
  53. public $is_gradebook_locked = false;
  54. public $exercise_was_added_in_lp = false;
  55. public $force_edit_exercise_in_lp = false;
  56. /**
  57. * Constructor of the class
  58. *
  59. * @author - Olivier Brouckaert
  60. */
  61. function Exercise($course_id = null) {
  62. $this->id = 0;
  63. $this->exercise = '';
  64. $this->description = '';
  65. $this->sound = '';
  66. $this->type = ALL_ON_ONE_PAGE;
  67. $this->random = 0;
  68. $this->random_answers = 0;
  69. $this->active = 1;
  70. $this->questionList = array();
  71. $this->timeLimit = 0;
  72. $this->end_time = '0000-00-00 00:00:00';
  73. $this->start_time = '0000-00-00 00:00:00';
  74. $this->results_disabled = 1;
  75. $this->expired_time = '0000-00-00 00:00:00';
  76. $this->propagate_neg = 0;
  77. $this->review_answers = false;
  78. $this->randomByCat = 0; //
  79. $this->text_when_finished = ""; //
  80. $this->display_category_name = 0;
  81. $this->pass_percentage = null;
  82. if (!empty($course_id)) {
  83. $course_info = api_get_course_info_by_id($course_id);
  84. } else {
  85. $course_info = api_get_course_info();
  86. }
  87. $this->course_id = $course_info['real_id'];
  88. $this->course = $course_info;
  89. }
  90. /**
  91. * reads exercise informations from the data base
  92. *
  93. * @author - Olivier Brouckaert
  94. * @param - integer $id - exercise ID
  95. * @return - boolean - true if exercise exists, otherwise false
  96. */
  97. function read($id) {
  98. global $_configuration;
  99. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  100. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  101. $id = intval($id);
  102. if (empty($this->course_id)) {
  103. return false;
  104. }
  105. $sql = "SELECT * FROM $TBL_EXERCICES WHERE c_id = ".$this->course_id." AND id = ".$id;
  106. $result = Database::query($sql);
  107. // if the exercise has been found
  108. if ($object = Database::fetch_object($result)) {
  109. $this->id = $id;
  110. $this->exercise = $object->title;
  111. $this->name = $object->title;
  112. $this->title = $object->title;
  113. $this->description = $object->description;
  114. $this->sound = $object->sound;
  115. $this->type = $object->type;
  116. $this->random = $object->random;
  117. $this->random_answers = $object->random_answers;
  118. $this->active = $object->active;
  119. $this->results_disabled = $object->results_disabled;
  120. $this->attempts = $object->max_attempt;
  121. $this->feedback_type = $object->feedback_type;
  122. $this->propagate_neg = $object->propagate_neg;
  123. $this->randomByCat = $object->random_by_category;
  124. $this->text_when_finished = $object->text_when_finished;
  125. $this->display_category_name = $object->display_category_name;
  126. $this->pass_percentage = $object->pass_percentage;
  127. $this->is_gradebook_locked = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
  128. $this->review_answers = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
  129. $sql = "SELECT max_score FROM $table_lp_item
  130. WHERE c_id = {$this->course_id} AND
  131. item_type = '".TOOL_QUIZ."' AND
  132. path = '".$id."'";
  133. $result = Database::query($sql);
  134. if (Database::num_rows($result) > 0) {
  135. $this->exercise_was_added_in_lp = true;
  136. }
  137. $this->force_edit_exercise_in_lp = isset($_configuration['force_edit_exercise_in_lp']) ? $_configuration['force_edit_exercise_in_lp'] : false;
  138. if ($this->exercise_was_added_in_lp) {
  139. $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
  140. } else {
  141. $this->edit_exercise_in_lp = true;
  142. }
  143. if ($object->end_time != '0000-00-00 00:00:00') {
  144. $this->end_time = $object->end_time;
  145. }
  146. if ($object->start_time != '0000-00-00 00:00:00') {
  147. $this->start_time = $object->start_time;
  148. }
  149. //control time
  150. $this->expired_time = $object->expired_time;
  151. //Checking if question_order is correctly set
  152. $this->questionList = $this->selectQuestionList(true);
  153. //overload questions list with recorded questions list
  154. //load questions only for exercises of type 'one question per page'
  155. //this is needed only is there is no questions
  156. /*
  157. // @todo not sure were in the code this is used somebody mess with the exercise tool
  158. // @todo don't know who add that config and why $_configuration['live_exercise_tracking']
  159. global $_configuration, $questionList;
  160. if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED') &&
  161. isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']) {
  162. //if(empty($_SESSION['questionList']))
  163. $this->questionList = $questionList;
  164. }*/
  165. return true;
  166. }
  167. // exercise not found
  168. return false;
  169. }
  170. function getCutTitle() {
  171. return cut($this->exercise, EXERCISE_MAX_NAME_SIZE);
  172. }
  173. /**
  174. * returns the exercise ID
  175. *
  176. * @author - Olivier Brouckaert
  177. * @return - integer - exercise ID
  178. */
  179. function selectId() {
  180. return $this->id;
  181. }
  182. /**
  183. * returns the exercise title
  184. *
  185. * @author - Olivier Brouckaert
  186. * @return - string - exercise title
  187. */
  188. function selectTitle() {
  189. return $this->exercise;
  190. }
  191. /**
  192. * returns the number of attempts setted
  193. *
  194. * @return - numeric - exercise attempts
  195. */
  196. function selectAttempts() {
  197. return $this->attempts;
  198. }
  199. /** returns the number of FeedbackType *
  200. * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  201. * @return - numeric - exercise attempts
  202. */
  203. function selectFeedbackType() {
  204. return $this->feedback_type;
  205. }
  206. /**
  207. * returns the time limit
  208. */
  209. function selectTimeLimit() {
  210. return $this->timeLimit;
  211. }
  212. /**
  213. * returns the exercise description
  214. *
  215. * @author - Olivier Brouckaert
  216. * @return - string - exercise description
  217. */
  218. function selectDescription() {
  219. return $this->description;
  220. }
  221. /**
  222. * returns the exercise sound file
  223. *
  224. * @author - Olivier Brouckaert
  225. * @return - string - exercise description
  226. */
  227. function selectSound() {
  228. return $this->sound;
  229. }
  230. /**
  231. * returns the exercise type
  232. *
  233. * @author - Olivier Brouckaert
  234. * @return - integer - exercise type
  235. */
  236. function selectType() {
  237. return $this->type;
  238. }
  239. /**
  240. * @author - hubert borderiou 30-11-11
  241. * @return - integer : do we display the question category name for students
  242. */
  243. function selectDisplayCategoryName() {
  244. return $this->display_category_name;
  245. }
  246. function selectPassPercentage() {
  247. return $this->pass_percentage;
  248. }
  249. /**
  250. * @author - hubert borderiou 30-11-11
  251. * @return - : modify object to update the switch display_category_name
  252. * $in_txt is an integer 0 or 1
  253. */
  254. function updateDisplayCategoryName($in_txt) {
  255. $this->display_category_name = $in_txt;
  256. }
  257. /**
  258. * @author - hubert borderiou 28-11-11
  259. * @return - html text : the text to display ay the end of the test.
  260. */
  261. function selectTextWhenFinished() {
  262. return $this->text_when_finished;
  263. }
  264. /**
  265. * @author - hubert borderiou 28-11-11
  266. * @return - html text : update the text to display ay the end of the test.
  267. */
  268. function updateTextWhenFinished($in_txt) {
  269. $this->text_when_finished = $in_txt;
  270. }
  271. /**
  272. * return 1 or 2 if randomByCat
  273. * @author - hubert borderiou
  274. * @return - integer - quiz random by category
  275. */
  276. function selectRandomByCat() {
  277. return $this->randomByCat;
  278. }
  279. /**
  280. * return 0 if no random by cat
  281. * return 1 if random by cat, categories shuffled
  282. * return 2 if random by cat, categories sorted by alphabetic order
  283. * @author - hubert borderiou
  284. * @return - integer - quiz random by category
  285. */
  286. function isRandomByCat() {
  287. $res = 0;
  288. if ($this->randomByCat == 1) {
  289. $res = 1;
  290. } else if ($this->randomByCat == 2) {
  291. $res = 2;
  292. }
  293. return $res;
  294. }
  295. /**
  296. * return nothing
  297. * update randomByCat value for object
  298. * @author - hubert borderiou
  299. */
  300. function updateRandomByCat($in_randombycat) {
  301. if ($in_randombycat == 1) {
  302. $this->randomByCat = 1;
  303. } else if ($in_randombycat == 2) {
  304. $this->randomByCat = 2;
  305. } else {
  306. $this->randomByCat = 0;
  307. }
  308. }
  309. /**
  310. * tells if questions are selected randomly, and if so returns the draws
  311. *
  312. * @author - Carlos Vargas
  313. * @return - integer - results disabled exercise
  314. */
  315. function selectResultsDisabled() {
  316. return $this->results_disabled;
  317. }
  318. /**
  319. * tells if questions are selected randomly, and if so returns the draws
  320. *
  321. * @author - Olivier Brouckaert
  322. * @return - integer - 0 if not random, otherwise the draws
  323. */
  324. function isRandom() {
  325. if ($this->random > 0 || $this->random == -1) {
  326. return true;
  327. } else {
  328. return false;
  329. }
  330. }
  331. /**
  332. * returns random answers status.
  333. *
  334. * @author - Juan Carlos Ra�a
  335. */
  336. function selectRandomAnswers() {
  337. return $this->random_answers;
  338. }
  339. /**
  340. * Same as isRandom() but has a name applied to values different than 0 or 1
  341. */
  342. function getShuffle() {
  343. return $this->random;
  344. }
  345. /**
  346. * returns the exercise status (1 = enabled ; 0 = disabled)
  347. *
  348. * @author - Olivier Brouckaert
  349. * @return - boolean - true if enabled, otherwise false
  350. */
  351. function selectStatus() {
  352. return $this->active;
  353. }
  354. /**
  355. * returns the array with the question ID list
  356. *
  357. * @author - Olivier Brouckaert
  358. * @return - array - question ID list
  359. */
  360. function selectQuestionList($from_db = false) {
  361. if ($from_db && !empty($this->id)) {
  362. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  363. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  364. $sql = "SELECT DISTINCT e.question_order
  365. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  366. ON (e.question_id = q.id AND e.c_id = ".$this->course_id." AND q.c_id = ".$this->course_id.")
  367. WHERE e.exercice_id = '".Database::escape_string($this->id)."'";
  368. $result = Database::query($sql);
  369. $count_question_orders = Database::num_rows($result);
  370. $sql = "SELECT e.question_id, e.question_order
  371. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  372. ON (e.question_id = q.id AND e.c_id = ".$this->course_id." AND q.c_id = ".$this->course_id.")
  373. WHERE e.exercice_id = '".Database::escape_string($this->id)."'
  374. ORDER BY question_order";
  375. $result = Database::query($sql);
  376. // fills the array with the question ID for this exercise
  377. // the key of the array is the question position
  378. $temp_question_list = array();
  379. $counter = 1;
  380. $question_list = array();
  381. while ($new_object = Database::fetch_object($result)) {
  382. $question_list[$new_object->question_order]= $new_object->question_id;
  383. $temp_question_list[$counter] = $new_object->question_id;
  384. $counter++;
  385. }
  386. if (!empty($temp_question_list)) {
  387. if (count($temp_question_list) != $count_question_orders) {
  388. $question_list = $temp_question_list;
  389. }
  390. }
  391. return $question_list;
  392. }
  393. return $this->questionList;
  394. }
  395. /**
  396. * returns the number of questions in this exercise
  397. *
  398. * @author - Olivier Brouckaert
  399. * @return - integer - number of questions
  400. */
  401. function selectNbrQuestions() {
  402. return sizeof($this->questionList);
  403. }
  404. function selectPropagateNeg() {
  405. return $this->propagate_neg;
  406. }
  407. /**
  408. * Selects questions randomly in the question list
  409. *
  410. * @author - Olivier Brouckaert
  411. * @return - array - if the exercise is not set to take questions randomly, returns the question list
  412. * without randomizing, otherwise, returns the list with questions selected randomly
  413. * Modified by Hubert Borderiou 15 nov 2011
  414. */
  415. function selectRandomList() {
  416. $nbQuestions = $this->selectNbrQuestions();
  417. $temp_list = $this->questionList;
  418. //Not a random exercise, or if there are not at least 2 questions
  419. if($this->random == 0 || $nbQuestions < 2) {
  420. return $this->questionList;
  421. }
  422. if ($nbQuestions != 0) {
  423. shuffle($temp_list);
  424. $my_random_list = array_combine(range(1,$nbQuestions),$temp_list);
  425. $my_question_list = array();
  426. // $this->random == -1 if random with all questions
  427. if ($this->random > 0) {
  428. $i = 0;
  429. foreach ($my_random_list as $item) {
  430. if ($i < $this->random) {
  431. $my_question_list[$i] = $item;
  432. } else {
  433. break;
  434. }
  435. $i++;
  436. }
  437. } else {
  438. $my_question_list = $my_random_list;
  439. }
  440. return $my_question_list;
  441. }
  442. }
  443. /**
  444. * returns 'true' if the question ID is in the question list
  445. *
  446. * @author - Olivier Brouckaert
  447. * @param - integer $questionId - question ID
  448. * @return - boolean - true if in the list, otherwise false
  449. */
  450. function isInList($questionId) {
  451. if (is_array($this->questionList))
  452. return in_array($questionId,$this->questionList);
  453. else
  454. return false;
  455. }
  456. /**
  457. * changes the exercise title
  458. *
  459. * @author - Olivier Brouckaert
  460. * @param - string $title - exercise title
  461. */
  462. function updateTitle($title) {
  463. $this->exercise=$title;
  464. }
  465. /**
  466. * changes the exercise max attempts
  467. *
  468. * @param - numeric $attempts - exercise max attempts
  469. */
  470. function updateAttempts($attempts) {
  471. $this->attempts=$attempts;
  472. }
  473. /**
  474. * changes the exercise feedback type
  475. *
  476. * @param - numeric $attempts - exercise max attempts
  477. */
  478. function updateFeedbackType($feedback_type) {
  479. $this->feedback_type=$feedback_type;
  480. }
  481. /**
  482. * changes the exercise description
  483. *
  484. * @author - Olivier Brouckaert
  485. * @param - string $description - exercise description
  486. */
  487. function updateDescription($description) {
  488. $this->description=$description;
  489. }
  490. /**
  491. * changes the exercise expired_time
  492. *
  493. * @author - Isaac flores
  494. * @param - int The expired time of the quiz
  495. */
  496. function updateExpiredTime($expired_time) {
  497. $this->expired_time = $expired_time;
  498. }
  499. function updatePropagateNegative($value) {
  500. $this->propagate_neg = $value;
  501. }
  502. function updateReviewAnswers($value) {
  503. $this->review_answers = (isset($value) && $value) ? true : false;
  504. }
  505. function updatePassPercentage($value) {
  506. $this->pass_percentage = $value;
  507. }
  508. /**
  509. * changes the exercise sound file
  510. *
  511. * @author - Olivier Brouckaert
  512. * @param - string $sound - exercise sound file
  513. * @param - string $delete - ask to delete the file
  514. */
  515. function updateSound($sound,$delete) {
  516. global $audioPath, $documentPath;
  517. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  518. if ($sound['size'] && (strstr($sound['type'],'audio') || strstr($sound['type'],'video'))) {
  519. $this->sound=$sound['name'];
  520. if (@move_uploaded_file($sound['tmp_name'],$audioPath.'/'.$this->sound)) {
  521. $query="SELECT 1 FROM $TBL_DOCUMENT WHERE c_id = ".$this->course_id." AND path='".str_replace($documentPath,'',$audioPath).'/'.$this->sound."'";
  522. $result=Database::query($query);
  523. if(!Database::num_rows($result)) {
  524. /*$query="INSERT INTO $TBL_DOCUMENT(path,filetype) VALUES "
  525. ." ('".str_replace($documentPath,'',$audioPath).'/'.$this->sound."','file')";
  526. Database::query($query);*/
  527. $id = add_document($this->course,str_replace($documentPath,'',$audioPath).'/'.$this->sound,'file',$sound['size'],$sound['name']);
  528. api_item_property_update($this->course, TOOL_DOCUMENT, $id, 'DocumentAdded',api_get_user_id());
  529. item_property_update_on_folder($this->course,str_replace($documentPath,'',$audioPath),api_get_user_id());
  530. }
  531. }
  532. } elseif($delete && is_file($audioPath.'/'.$this->sound)) {
  533. $this->sound='';
  534. }
  535. }
  536. /**
  537. * changes the exercise type
  538. *
  539. * @author - Olivier Brouckaert
  540. * @param - integer $type - exercise type
  541. */
  542. function updateType($type) {
  543. $this->type=$type;
  544. }
  545. /**
  546. * sets to 0 if questions are not selected randomly
  547. * if questions are selected randomly, sets the draws
  548. *
  549. * @author - Olivier Brouckaert
  550. * @param - integer $random - 0 if not random, otherwise the draws
  551. */
  552. function setRandom($random) {
  553. /*if ($random == 'all') {
  554. $random = $this->selectNbrQuestions();
  555. }*/
  556. $this->random = $random;
  557. }
  558. /**
  559. * sets to 0 if answers are not selected randomly
  560. * if answers are selected randomly
  561. * @author - Juan Carlos Ra�a
  562. * @param - integer $random_answers - random answers
  563. */
  564. function updateRandomAnswers($random_answers) {
  565. $this->random_answers = $random_answers;
  566. }
  567. /**
  568. * enables the exercise
  569. *
  570. * @author - Olivier Brouckaert
  571. */
  572. function enable() {
  573. $this->active=1;
  574. }
  575. /**
  576. * disables the exercise
  577. *
  578. * @author - Olivier Brouckaert
  579. */
  580. function disable() {
  581. $this->active=0;
  582. }
  583. function disable_results() {
  584. $this->results_disabled = true;
  585. }
  586. function enable_results() {
  587. $this->results_disabled = false;
  588. }
  589. function updateResultsDisabled($results_disabled) {
  590. $this->results_disabled = intval($results_disabled);
  591. }
  592. /**
  593. * updates the exercise in the data base
  594. *
  595. * @author - Olivier Brouckaert
  596. */
  597. function save($type_e = '') {
  598. global $_course;
  599. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  600. $id = $this->id;
  601. $exercise = $this->exercise;
  602. $description = $this->description;
  603. $sound = $this->sound;
  604. $type = $this->type;
  605. $attempts = $this->attempts;
  606. $feedback_type = $this->feedback_type;
  607. $random = $this->random;
  608. $random_answers = $this->random_answers;
  609. $active = $this->active;
  610. $propagate_neg = $this->propagate_neg;
  611. $review_answers = (isset($this->review_answers) && $this->review_answers) ? 1 : 0;
  612. $randomByCat = $this->randomByCat;
  613. $text_when_finished = $this->text_when_finished;
  614. $display_category_name = intval($this->display_category_name);
  615. $pass_percentage = intval($this->pass_percentage);
  616. $session_id = api_get_session_id();
  617. //If direct we do not show results
  618. if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  619. $results_disabled = 0;
  620. } else {
  621. $results_disabled = intval($this->results_disabled);
  622. }
  623. $expired_time = intval($this->expired_time);
  624. if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
  625. $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
  626. } else {
  627. $start_time = '0000-00-00 00:00:00';
  628. }
  629. if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
  630. $end_time = Database::escape_string(api_get_utc_datetime($this->end_time));
  631. } else {
  632. $end_time = '0000-00-00 00:00:00';
  633. }
  634. // Exercise already exists
  635. if ($id) {
  636. $sql="UPDATE $TBL_EXERCICES SET
  637. title='".Database::escape_string($exercise)."',
  638. description='".Database::escape_string($description)."'";
  639. if ($type_e != 'simple') {
  640. $sql .= ",sound='".Database::escape_string($sound)."',
  641. type ='".Database::escape_string($type)."',
  642. random ='".Database::escape_string($random)."',
  643. random_answers ='".Database::escape_string($random_answers)."',
  644. active ='".Database::escape_string($active)."',
  645. feedback_type ='".Database::escape_string($feedback_type)."',
  646. start_time = '$start_time',
  647. end_time = '$end_time',
  648. max_attempt ='".Database::escape_string($attempts)."',
  649. expired_time ='".Database::escape_string($expired_time)."',
  650. propagate_neg ='".Database::escape_string($propagate_neg)."',
  651. review_answers ='".Database::escape_string($review_answers)."',
  652. random_by_category='".Database::escape_string($randomByCat)."',
  653. text_when_finished = '".Database::escape_string($text_when_finished)."',
  654. display_category_name = '".Database::escape_string($display_category_name)."',
  655. pass_percentage = '".Database::escape_string($pass_percentage)."',
  656. results_disabled='".Database::escape_string($results_disabled)."'";
  657. }
  658. $sql .= " WHERE c_id = ".$this->course_id." AND id='".Database::escape_string($id)."'";
  659. Database::query($sql);
  660. // update into the item_property table
  661. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizUpdated',api_get_user_id());
  662. if (api_get_setting('search_enabled')=='true') {
  663. $this->search_engine_edit();
  664. }
  665. } else {
  666. // creates a new exercise
  667. $sql = "INSERT INTO $TBL_EXERCICES (c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,
  668. results_disabled, max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,
  669. text_when_finished, display_category_name, pass_percentage)
  670. VALUES(
  671. ".$this->course_id.",
  672. '$start_time','$end_time',
  673. '".Database::escape_string($exercise)."',
  674. '".Database::escape_string($description)."',
  675. '".Database::escape_string($sound)."',
  676. '".Database::escape_string($type)."',
  677. '".Database::escape_string($random)."',
  678. '".Database::escape_string($random_answers)."',
  679. '".Database::escape_string($active)."',
  680. '".Database::escape_string($results_disabled)."',
  681. '".Database::escape_string($attempts)."',
  682. '".Database::escape_string($feedback_type)."',
  683. '".Database::escape_string($expired_time)."',
  684. '".Database::escape_string($session_id)."',
  685. '".Database::escape_string($review_answers)."',
  686. '".Database::escape_string($randomByCat)."',
  687. '".Database::escape_string($text_when_finished)."',
  688. '".Database::escape_string($display_category_name)."',
  689. '".Database::escape_string($pass_percentage)."'
  690. )";
  691. Database::query($sql);
  692. $this->id = Database::insert_id();
  693. // insert into the item_property table
  694. api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
  695. api_set_default_visibility($this->id, TOOL_QUIZ);
  696. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  697. $this->search_engine_save();
  698. }
  699. }
  700. // updates the question position
  701. $this->update_question_positions();
  702. }
  703. /* Updates question position */
  704. function update_question_positions() {
  705. $quiz_question_table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  706. //Fixes #3483 when updating order
  707. $question_list = $this->selectQuestionList(true);
  708. if (!empty($question_list)) {
  709. foreach ($question_list as $position => $questionId) {
  710. $sql="UPDATE $quiz_question_table SET question_order ='".intval($position)."'".
  711. "WHERE c_id = ".$this->course_id." AND question_id = ".intval($questionId)." AND exercice_id=".intval($this->id);
  712. Database::query($sql);
  713. }
  714. }
  715. }
  716. /**
  717. * Adds a question into the question list
  718. *
  719. * @author - Olivier Brouckaert
  720. * @param - integer $questionId - question ID
  721. * @return - boolean - true if the question has been added, otherwise false
  722. */
  723. function addToList($questionId) {
  724. // checks if the question ID is not in the list
  725. if(!$this->isInList($questionId)) {
  726. // selects the max position
  727. if(!$this->selectNbrQuestions()) {
  728. $pos=1;
  729. } else {
  730. if (is_array($this->questionList))
  731. $pos=max(array_keys($this->questionList))+1;
  732. }
  733. $this->questionList[$pos]=$questionId;
  734. return true;
  735. }
  736. return false;
  737. }
  738. /**
  739. * removes a question from the question list
  740. *
  741. * @author - Olivier Brouckaert
  742. * @param - integer $questionId - question ID
  743. * @return - boolean - true if the question has been removed, otherwise false
  744. */
  745. function removeFromList($questionId) {
  746. // searches the position of the question ID in the list
  747. $pos = array_search($questionId,$this->questionList);
  748. // question not found
  749. if ($pos === false) {
  750. return false;
  751. } else {
  752. // dont reduce the number of random question if we use random by category option, or if
  753. // random all questions
  754. if ($this->isRandom() && $this->isRandomByCat() == 0) {
  755. if (count($this->questionList) >= $this->random && $this->random > 0) {
  756. $this->random -= 1;
  757. $this->save();
  758. }
  759. }
  760. // deletes the position from the array containing the wanted question ID
  761. unset($this->questionList[$pos]);
  762. return true;
  763. }
  764. }
  765. /**
  766. * deletes the exercise from the database
  767. * Notice : leaves the question in the data base
  768. *
  769. * @author - Olivier Brouckaert
  770. */
  771. function delete() {
  772. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  773. $sql="UPDATE $TBL_EXERCICES SET active='-1' WHERE c_id = ".$this->course_id." AND id='".Database::escape_string($this->id)."'";
  774. Database::query($sql);
  775. api_item_property_update($this->course, TOOL_QUIZ, $this->id,'QuizDeleted',api_get_user_id());
  776. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian') ) {
  777. $this->search_engine_delete();
  778. }
  779. }
  780. /**
  781. * Creates the form to create / edit an exercise
  782. * @param FormValidator $form the formvalidator instance (by reference)
  783. */
  784. function createForm ($form, $type='full') {
  785. global $id;
  786. if (empty($type)){
  787. $type='full';
  788. }
  789. // form title
  790. if (!empty($_GET['exerciseId'])) {
  791. $form_title = get_lang('ModifyExercise');
  792. } else {
  793. $form_title = get_lang('NewEx');
  794. }
  795. $form->addElement('header', $form_title);
  796. // title
  797. $form->addElement('text', 'exerciseTitle', get_lang('ExerciseName'), array('class' => 'span6','id'=>'exercise_title'));
  798. //$form->applyFilter('exerciseTitle','html_filter');
  799. $form->addElement('advanced_settings','
  800. <a href="javascript://" onclick=" return show_media()">
  801. <span id="media_icon">
  802. <img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" /> '.addslashes(api_htmlentities(get_lang('ExerciseDescription'))).'
  803. </span>
  804. </a>
  805. ');
  806. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  807. if (is_array($type)){
  808. $editor_config = array_merge($editor_config, $type);
  809. }
  810. $form->addElement ('html','<div class="HideFCKEditor" id="HiddenFCKexerciseDescription" >');
  811. $form->add_html_editor('exerciseDescription', get_lang('ExerciseDescription'), false, false, $editor_config);
  812. $form->addElement ('html','</div>');
  813. $form->addElement('advanced_settings','<a href="javascript://" onclick=" return advanced_parameters()"><span id="img_plus_and_minus"><div style="vertical-align:top;" >
  814. <img style="vertical-align:middle;" src="../img/div_show.gif" alt="" /> '.addslashes(api_htmlentities(get_lang('AdvancedParameters'))).'</div></span></a>');
  815. // Random questions
  816. // style="" and not "display:none" to avoid #4029 Random and number of attempt menu empty
  817. $form->addElement('html','<div id="options" style="">');
  818. if ($type=='full') {
  819. /*$feedback_option[0]=get_lang('ExerciseAtTheEndOfTheTest');
  820. $feedback_option[1]=get_lang('DirectFeedback');
  821. $feedback_option[2]=get_lang('NoFeedback');
  822. */
  823. //Can't modify a DirectFeedback question
  824. if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT ) {
  825. // feedback type
  826. $radios_feedback = array();
  827. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0',array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
  828. if (api_get_setting('enable_quiz_scenario') == 'true') {
  829. //Can't convert a question from one feedback to another if there is more than 1 question already added
  830. if ($this->selectNbrQuestions() == 0) {
  831. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'),'1',array('id' =>'exerciseType_1' , 'onclick' => 'check_direct_feedback()'));
  832. }
  833. }
  834. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2',array('id' =>'exerciseType_2'));
  835. $form->addGroup($radios_feedback, null, get_lang('FeedbackType'), '');
  836. //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  837. // test type
  838. $radios = array();
  839. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
  840. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
  841. $form->addGroup($radios, null, get_lang('QuestionsPerPage'), '');
  842. $radios_results_disabled = array();
  843. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  844. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
  845. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
  846. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
  847. } else {
  848. // if is Directfeedback but has not questions we can allow to modify the question type
  849. if ($this->selectNbrQuestions() == 0) {
  850. // feedback type
  851. $radios_feedback = array();
  852. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0',array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
  853. if (api_get_setting('enable_quiz_scenario') == 'true') {
  854. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'), '1', array('id' =>'exerciseType_1' , 'onclick' => 'check_direct_feedback()'));
  855. }
  856. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2',array('id' =>'exerciseType_2'));
  857. $form->addGroup($radios_feedback, null, get_lang('FeedbackType'));
  858. //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  859. // test type
  860. $radios = array();
  861. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1');
  862. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2');
  863. $form->addGroup($radios, null, get_lang('ExerciseType'));
  864. $radios_results_disabled = array();
  865. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  866. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
  867. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
  868. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'),'');
  869. } else {
  870. //Show options freeze
  871. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  872. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
  873. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
  874. $result_disable_group = $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'),'');
  875. $result_disable_group->freeze();
  876. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
  877. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
  878. $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'), '');
  879. $type_group->freeze();
  880. //we force the options to the DirectFeedback exercisetype
  881. $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
  882. $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
  883. }
  884. }
  885. // number of random question
  886. $option = array();
  887. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10 ;
  888. $option = range(0,$max);
  889. $option[0] = get_lang('No');
  890. $option[-1] = get_lang('AllQuestionsShort');
  891. $form->addElement('select', 'randomQuestions',array(get_lang('RandomQuestions'), get_lang('RandomQuestionsHelp')), $option, array('id'=>'randomQuestions','class'=>'chzn-select'));
  892. //random answers
  893. $radios_random_answers = array();
  894. $radios_random_answers[] = $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'),'1');
  895. $radios_random_answers[] = $form->createElement('radio', 'randomAnswers', null, get_lang('No'),'0');
  896. $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'), '');
  897. //randow by category
  898. $form->addElement('html','<div class="clear">&nbsp;</div>');
  899. $radiocat = array();
  900. $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesShuffled'),'1');
  901. $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesSorted'),'2');
  902. $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('No'),'0');
  903. $form->addGroup($radiocat, null, get_lang('RandomQuestionByCategory'), '');
  904. $form->addElement('html','<div class="clear">&nbsp;</div>');
  905. // add the radio display the category name for student
  906. $radio_display_cat_name = array();
  907. $radio_display_cat_name[] = $form->createElement('radio', 'display_category_name', null, get_lang('Yes'),'1');
  908. $radio_display_cat_name[] = $form->createElement('radio', 'display_category_name', null, get_lang('No'),'0');
  909. $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'), '');
  910. //Attempts
  911. $attempt_option=range(0,10);
  912. $attempt_option[0]=get_lang('Infinite');
  913. $form->addElement('select', 'exerciseAttempts',get_lang('ExerciseAttempts'),$attempt_option, array('id'=>'exerciseAttempts','class'=>'chzn-select'));
  914. // Exercice time limit
  915. $form->addElement('checkbox', 'activate_start_date_check',null, get_lang('EnableStartTime'), array('onclick' => 'activate_start_date()'));
  916. $var = Exercise::selectTimeLimit();
  917. if (($this->start_time != '0000-00-00 00:00:00'))
  918. $form->addElement('html','<div id="start_date_div" style="display:block;">');
  919. else
  920. $form->addElement('html','<div id="start_date_div" style="display:none;">');
  921. $form->addElement('datepicker', 'start_time', '', array('form_name'=>'exercise_admin'), 5);
  922. $form->addElement('html','</div>');
  923. $form->addElement('checkbox', 'activate_end_date_check', null , get_lang('EnableEndTime'), array('onclick' => 'activate_end_date()'));
  924. if (($this->end_time != '0000-00-00 00:00:00'))
  925. $form->addElement('html','<div id="end_date_div" style="display:block;">');
  926. else
  927. $form->addElement('html','<div id="end_date_div" style="display:none;">');
  928. $form->addElement('datepicker', 'end_time', '', array('form_name'=>'exercise_admin'), 5);
  929. $form->addElement('html','</div>');
  930. //$check_option=$this->selectType();
  931. $diplay = 'block';
  932. $form->addElement('checkbox', 'propagate_neg', null, get_lang('PropagateNegativeResults'));
  933. $form->addElement('html','<div class="clear">&nbsp;</div>');
  934. $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
  935. $form->addElement('html','<div id="divtimecontrol" style="display:'.$diplay.';">');
  936. //Timer control
  937. //$time_hours_option = range(0,12);
  938. //$time_minutes_option = range(0,59);
  939. $form->addElement('checkbox', 'enabletimercontrol', null, get_lang('EnableTimerControl'), array('onclick' =>'option_time_expired()','id'=>'enabletimercontrol','onload'=>'check_load_time()'));
  940. $expired_date = (int)$this->selectExpiredTime();
  941. if (($expired_date!='0')) {
  942. $form->addElement('html','<div id="timercontrol" style="display:block;">');
  943. } else {
  944. $form->addElement('html','<div id="timercontrol" style="display:none;">');
  945. }
  946. $form->addElement('text', 'enabletimercontroltotalminutes',get_lang('ExerciseTotalDurationInMinutes'),array('style' => 'width : 35px','id' => 'enabletimercontroltotalminutes'));
  947. $form->addElement('html','</div>');
  948. //Pass percentage
  949. /*$options = array('' => '-');
  950. for ($i = 0; $i <= 20 ; $i++) {
  951. $options[$i*5] = $i*5;
  952. }
  953. $form->addElement('select', 'pass_percentage', array(get_lang('PassPercentage'), null, '%'), $options, array('id' => 'pass_percentage', 'class' => 'chzn-select'));
  954. */
  955. $form->addElement('text', 'pass_percentage', array(get_lang('PassPercentage'), null, '%'), array('id' => 'pass_percentage'));
  956. $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
  957. //$form->addElement('text', 'exerciseAttempts', get_lang('ExerciseAttempts').' : ',array('size'=>'2'));
  958. // add the text_when_finished textbox
  959. $form -> add_html_editor('text_when_finished', get_lang('TextWhenFinished'), false, false, $editor_config);
  960. $defaults = array();
  961. if (api_get_setting('search_enabled') === 'true') {
  962. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  963. $form->addElement ('checkbox', 'index_document','', get_lang('SearchFeatureDoIndexDocument'));
  964. //$form->addElement ('html', '<div class="label">'. get_lang('SearchFeatureDocumentLanguage') .'</div>');
  965. //$form->addElement ('html', '<div class="formw">'. api_get_languages_combo() .'</div>');
  966. $form->addElement ('select_language', 'language', get_lang('SearchFeatureDocumentLanguage'));
  967. //$form->addElement ('html','</div><div class="sub-form">');
  968. $specific_fields = get_specific_field_list();
  969. foreach ($specific_fields as $specific_field) {
  970. $form->addElement ('text', $specific_field['code'], $specific_field['name']);
  971. $filter = array('c_id'=> "'". api_get_course_int_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $this->id, 'tool_id' => '\''. TOOL_QUIZ .'\'');
  972. $values = get_specific_field_values_list($filter, array('value'));
  973. if ( !empty($values) ) {
  974. $arr_str_values = array();
  975. foreach ($values as $value) {
  976. $arr_str_values[] = $value['value'];
  977. }
  978. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  979. }
  980. }
  981. //$form->addElement ('html','</div>');
  982. }
  983. $form->addElement('html','</div>'); //End advanced setting
  984. $form->addElement('html','</div>');
  985. }
  986. // submit
  987. isset($_GET['exerciseId'])?$text=get_lang('ModifyExercise'):$text=get_lang('ProcedToQuestions');
  988. $form->addElement('style_submit_button', 'submitExercise', $text, 'class="save"');
  989. $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  990. if ($type == 'full') {
  991. // rules
  992. $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
  993. $form->addRule('start_time', get_lang('InvalidDate'), 'date');
  994. $form->addRule('end_time', get_lang('InvalidDate'), 'date');
  995. //$form->addRule(array ('start_time', 'end_time'), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
  996. }
  997. // defaults
  998. if ($type=='full') {
  999. if ($this->id > 0) {
  1000. if ($this->random > $this->selectNbrQuestions()) {
  1001. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  1002. } else {
  1003. $defaults['randomQuestions'] = $this->random;
  1004. }
  1005. $defaults['randomAnswers'] = $this->selectRandomAnswers();
  1006. $defaults['exerciseType'] = $this->selectType();
  1007. $defaults['exerciseTitle'] = $this->selectTitle();
  1008. $defaults['exerciseDescription'] = $this->selectDescription();
  1009. $defaults['exerciseAttempts'] = $this->selectAttempts();
  1010. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  1011. $defaults['results_disabled'] = $this->selectResultsDisabled();
  1012. $defaults['propagate_neg'] = $this->selectPropagateNeg();
  1013. $defaults['review_answers'] = $this->review_answers;
  1014. $defaults['randomByCat'] = $this->selectRandomByCat(); //
  1015. $defaults['text_when_finished'] = $this->selectTextWhenFinished(); //
  1016. $defaults['display_category_name'] = $this->selectDisplayCategoryName(); //
  1017. $defaults['pass_percentage'] = $this->selectPassPercentage();
  1018. if (($this->start_time != '0000-00-00 00:00:00'))
  1019. $defaults['activate_start_date_check'] = 1;
  1020. if ($this->end_time != '0000-00-00 00:00:00')
  1021. $defaults['activate_end_date_check'] = 1;
  1022. $defaults['start_time'] = ($this->start_time!='0000-00-00 00:00:00') ? api_get_local_time($this->start_time) : date('Y-m-d 12:00:00');
  1023. $defaults['end_time'] = ($this->end_time!='0000-00-00 00:00:00') ? api_get_local_time($this->end_time) : date('Y-m-d 12:00:00', time()+84600);
  1024. //Get expired time
  1025. if($this->expired_time != '0') {
  1026. $defaults['enabletimercontrol'] = 1;
  1027. $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
  1028. } else {
  1029. $defaults['enabletimercontroltotalminutes'] = 0;
  1030. }
  1031. } else {
  1032. $defaults['exerciseType'] = 2;
  1033. $defaults['exerciseAttempts'] = 0;
  1034. $defaults['randomQuestions'] = 0;
  1035. $defaults['randomAnswers'] = 0;
  1036. $defaults['exerciseDescription'] = '';
  1037. $defaults['exerciseFeedbackType'] = 0;
  1038. $defaults['results_disabled'] = 0;
  1039. $defaults['randomByCat'] = 0; //
  1040. $defaults['text_when_finished'] = ""; //
  1041. $defaults['start_time'] = date('Y-m-d 12:00:00');
  1042. $defaults['display_category_name'] = 1; //
  1043. $defaults['end_time'] = date('Y-m-d 12:00:00',time()+84600);
  1044. $defaults['pass_percentage'] = '';
  1045. }
  1046. } else {
  1047. $defaults['exerciseTitle'] = $this->selectTitle();
  1048. $defaults['exerciseDescription'] = $this->selectDescription();
  1049. }
  1050. if (api_get_setting('search_enabled') === 'true') {
  1051. $defaults['index_document'] = 'checked="checked"';
  1052. }
  1053. $form->setDefaults($defaults);
  1054. }
  1055. /**
  1056. * function which process the creation of exercises
  1057. * @param FormValidator $form the formvalidator instance
  1058. */
  1059. function processCreation($form, $type='') {
  1060. $this->updateTitle($form->getSubmitValue('exerciseTitle'));
  1061. $this->updateDescription($form->getSubmitValue('exerciseDescription'));
  1062. $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
  1063. $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
  1064. $this->updateType($form->getSubmitValue('exerciseType'));
  1065. $this->setRandom($form->getSubmitValue('randomQuestions'));
  1066. $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  1067. $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
  1068. $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
  1069. $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  1070. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  1071. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  1072. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  1073. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  1074. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  1075. if ($form->getSubmitValue('activate_start_date_check') == 1) {
  1076. $start_time = $form->getSubmitValue('start_time');
  1077. $start_time['F'] = sprintf('%02d', $start_time['F']);
  1078. $start_time['i'] = sprintf('%02d', $start_time['i']);
  1079. $start_time['d'] = sprintf('%02d', $start_time['d']);
  1080. $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
  1081. } else {
  1082. $this->start_time = '0000-00-00 00:00:00';
  1083. }
  1084. if ($form->getSubmitValue('activate_end_date_check') == 1) {
  1085. $end_time = $form->getSubmitValue('end_time');
  1086. $end_time['F'] = sprintf('%02d', $end_time['F']);
  1087. $end_time['i'] = sprintf('%02d', $end_time['i']);
  1088. $end_time['d'] = sprintf('%02d', $end_time['d']);
  1089. $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
  1090. } else {
  1091. $this->end_time = '0000-00-00 00:00:00';
  1092. }
  1093. if ($form->getSubmitValue('enabletimercontrol') == 1) {
  1094. $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
  1095. if ($this->expired_time == 0) {
  1096. $this->expired_time = $expired_total_time;
  1097. }
  1098. } else {
  1099. $this->expired_time = 0;
  1100. }
  1101. if ($form->getSubmitValue('randomAnswers') == 1) {
  1102. $this->random_answers=1;
  1103. } else {
  1104. $this->random_answers=0;
  1105. }
  1106. $this->save($type);
  1107. }
  1108. function search_engine_save() {
  1109. if ($_POST['index_document'] != 1) {
  1110. return;
  1111. }
  1112. $course_id = api_get_course_id();
  1113. require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
  1114. require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
  1115. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  1116. $specific_fields = get_specific_field_list();
  1117. $ic_slide = new IndexableChunk();
  1118. $all_specific_terms = '';
  1119. foreach ($specific_fields as $specific_field) {
  1120. if (isset($_REQUEST[$specific_field['code']])) {
  1121. $sterms = trim($_REQUEST[$specific_field['code']]);
  1122. if (!empty($sterms)) {
  1123. $all_specific_terms .= ' '. $sterms;
  1124. $sterms = explode(',', $sterms);
  1125. foreach ($sterms as $sterm) {
  1126. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1127. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1128. }
  1129. }
  1130. }
  1131. }
  1132. // build the chunk to index
  1133. $ic_slide->addValue("title", $this->exercise);
  1134. $ic_slide->addCourseId($course_id);
  1135. $ic_slide->addToolId(TOOL_QUIZ);
  1136. $xapian_data = array(
  1137. SE_COURSE_ID => $course_id,
  1138. SE_TOOL_ID => TOOL_QUIZ,
  1139. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1140. SE_USER => (int)api_get_user_id(),
  1141. );
  1142. $ic_slide->xapian_data = serialize($xapian_data);
  1143. $exercise_description = $all_specific_terms .' '. $this->description;
  1144. $ic_slide->addValue("content", $exercise_description);
  1145. $di = new ChamiloIndexer();
  1146. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  1147. $di->connectDb(NULL, NULL, $lang);
  1148. $di->addChunk($ic_slide);
  1149. //index and return search engine document id
  1150. $did = $di->index();
  1151. if ($did) {
  1152. // save it to db
  1153. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1154. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1155. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1156. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1157. Database::query($sql);
  1158. }
  1159. }
  1160. function search_engine_edit() {
  1161. // update search enchine and its values table if enabled
  1162. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  1163. $course_id = api_get_course_id();
  1164. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  1165. // get search_did
  1166. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1167. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  1168. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1169. $res = Database::query($sql);
  1170. if (Database::num_rows($res) > 0) {
  1171. require_once(api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php');
  1172. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  1173. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  1174. $se_ref = Database::fetch_array($res);
  1175. $specific_fields = get_specific_field_list();
  1176. $ic_slide = new IndexableChunk();
  1177. $all_specific_terms = '';
  1178. foreach ($specific_fields as $specific_field) {
  1179. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  1180. if (isset($_REQUEST[$specific_field['code']])) {
  1181. $sterms = trim($_REQUEST[$specific_field['code']]);
  1182. $all_specific_terms .= ' '. $sterms;
  1183. $sterms = explode(',', $sterms);
  1184. foreach ($sterms as $sterm) {
  1185. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1186. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1187. }
  1188. }
  1189. }
  1190. // build the chunk to index
  1191. $ic_slide->addValue("title", $this->exercise);
  1192. $ic_slide->addCourseId($course_id);
  1193. $ic_slide->addToolId(TOOL_QUIZ);
  1194. $xapian_data = array(
  1195. SE_COURSE_ID => $course_id,
  1196. SE_TOOL_ID => TOOL_QUIZ,
  1197. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1198. SE_USER => (int)api_get_user_id(),
  1199. );
  1200. $ic_slide->xapian_data = serialize($xapian_data);
  1201. $exercise_description = $all_specific_terms .' '. $this->description;
  1202. $ic_slide->addValue("content", $exercise_description);
  1203. $di = new ChamiloIndexer();
  1204. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  1205. $di->connectDb(NULL, NULL, $lang);
  1206. $di->remove_document((int)$se_ref['search_did']);
  1207. $di->addChunk($ic_slide);
  1208. //index and return search engine document id
  1209. $did = $di->index();
  1210. if ($did) {
  1211. // save it to db
  1212. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  1213. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1214. Database::query($sql);
  1215. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1216. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1217. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1218. Database::query($sql);
  1219. }
  1220. } else {
  1221. $this->search_engine_save();
  1222. }
  1223. }
  1224. }
  1225. function search_engine_delete() {
  1226. // remove from search engine if enabled
  1227. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian') ) {
  1228. $course_id = api_get_course_id();
  1229. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1230. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  1231. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1232. $res = Database::query($sql);
  1233. if (Database::num_rows($res) > 0) {
  1234. $row = Database::fetch_array($res);
  1235. require_once(api_get_path(LIBRARY_PATH) .'search/ChamiloIndexer.class.php');
  1236. $di = new ChamiloIndexer();
  1237. $di->remove_document((int)$row['search_did']);
  1238. unset($di);
  1239. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1240. foreach ( $this->questionList as $question_i) {
  1241. $sql = 'SELECT type FROM %s WHERE id=%s';
  1242. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  1243. $qres = Database::query($sql);
  1244. if (Database::num_rows($qres) > 0) {
  1245. $qrow = Database::fetch_array($qres);
  1246. $objQuestion = Question::getInstance($qrow['type']);
  1247. $objQuestion = Question::read((int)$question_i);
  1248. $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
  1249. unset($objQuestion);
  1250. }
  1251. }
  1252. }
  1253. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  1254. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1255. Database::query($sql);
  1256. // remove terms from db
  1257. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  1258. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  1259. }
  1260. }
  1261. function selectExpiredTime() {
  1262. return $this->expired_time;
  1263. }
  1264. /**
  1265. * Cleans the student's results only for the Exercise tool (Not from the LP)
  1266. * The LP results are NOT deleted
  1267. * Works with exercises in sessions
  1268. * @return int quantity of user's exercises deleted
  1269. */
  1270. function clean_results() {
  1271. $table_track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1272. $table_track_e_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1273. $sql_select = "SELECT exe_id FROM $table_track_e_exercises
  1274. WHERE exe_cours_id = '".api_get_course_id()."' AND
  1275. exe_exo_id = ".$this->id." AND
  1276. orig_lp_id = 0 AND
  1277. orig_lp_item_id = 0 AND
  1278. session_id = ".api_get_session_id()."";
  1279. $result = Database::query($sql_select);
  1280. $exe_list = Database::store_result($result);
  1281. //deleting TRACK_E_ATTEMPT table
  1282. $i = 0;
  1283. if (is_array($exe_list) && count($exe_list) > 0) {
  1284. foreach($exe_list as $item) {
  1285. $sql = "DELETE FROM $table_track_e_attempt WHERE exe_id = '".$item['exe_id']."'";
  1286. Database::query($sql);
  1287. $i++;
  1288. }
  1289. }
  1290. //delete TRACK_E_EXERCICES table
  1291. $sql = "DELETE FROM $table_track_e_exercises
  1292. WHERE exe_cours_id = '".api_get_course_id()."' AND exe_exo_id = ".$this->id." AND orig_lp_id = 0 AND orig_lp_item_id = 0 AND session_id = ".api_get_session_id()."";
  1293. Database::query($sql);
  1294. return $i;
  1295. }
  1296. /**
  1297. * Copies an exercise (duplicate all questions and answers)
  1298. */
  1299. public function copy_exercise() {
  1300. $exercise_obj= new Exercise();
  1301. $exercise_obj = $this;
  1302. // force the creation of a new exercise
  1303. $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
  1304. //Hides the new exercise
  1305. $exercise_obj->updateStatus(false);
  1306. $exercise_obj->updateId(0);
  1307. $exercise_obj->save();
  1308. $new_exercise_id = $exercise_obj->selectId();
  1309. $question_list = $exercise_obj->selectQuestionList();
  1310. if (!empty($question_list)) {
  1311. //Question creation
  1312. foreach ($question_list as $old_question_id) {
  1313. $old_question_obj = Question::read($old_question_id);
  1314. $new_id = $old_question_obj->duplicate();
  1315. if ($new_id) {
  1316. $new_question_obj = Question::read($new_id);
  1317. if (isset($new_question_obj) && $new_question_obj) {
  1318. $new_question_obj->addToList($new_exercise_id);
  1319. // This should be moved to the duplicate function
  1320. $new_answer_obj = new Answer($old_question_id);
  1321. $new_answer_obj->read();
  1322. $new_answer_obj->duplicate($new_id);
  1323. }
  1324. }
  1325. }
  1326. }
  1327. }
  1328. /**
  1329. * Changes the exercise id
  1330. *
  1331. * @param - in $id - exercise id
  1332. */
  1333. private function updateId($id) {
  1334. $this->id = $id;
  1335. }
  1336. /**
  1337. * Changes the exercise status
  1338. *
  1339. * @param - string $status - exercise status
  1340. */
  1341. function updateStatus($status) {
  1342. $this->active = $status;
  1343. }
  1344. public function get_stat_track_exercise_info($lp_id = 0, $lp_item_id = 0, $lp_item_view_id = 0, $status = 'incomplete') {
  1345. $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1346. if (empty($lp_id)) {
  1347. $lp_id = 0;
  1348. }
  1349. if (empty($lp_item_id)) {
  1350. $lp_item_id = 0;
  1351. }
  1352. if (empty($lp_item_view_id)) {
  1353. $lp_item_view_id = 0;
  1354. }
  1355. $condition = ' WHERE exe_exo_id = ' . "'" . $this->id . "'" .' AND
  1356. exe_user_id = ' . "'" . api_get_user_id() . "'" . ' AND
  1357. exe_cours_id = ' . "'" . api_get_course_id() . "'" . ' AND
  1358. status = ' . "'" . Database::escape_string($status). "'" . ' AND
  1359. orig_lp_id = ' . "'" . $lp_id . "'" . ' AND
  1360. orig_lp_item_id = ' . "'" . $lp_item_id . "'" . ' AND
  1361. orig_lp_item_view_id = ' . "'" . $lp_item_view_id . "'" . ' AND
  1362. session_id = ' . "'" . api_get_session_id() . "' LIMIT 1"; //Adding limit 1 just in case
  1363. $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
  1364. $result = Database::query($sql_track);
  1365. $new_array = array();
  1366. if (Database::num_rows($result) > 0 ) {
  1367. $new_array = Database::fetch_array($result, 'ASSOC');
  1368. }
  1369. return $new_array;
  1370. }
  1371. /**
  1372. * Saves a test attempt
  1373. *
  1374. * @param int clock_expired_time
  1375. * @param int lp id
  1376. * @param int lp item id
  1377. * @param int lp item_view id
  1378. * @param array question list
  1379. */
  1380. public function save_stat_track_exercise_info($clock_expired_time = 0, $safe_lp_id = 0, $safe_lp_item_id = 0, $safe_lp_item_view_id = 0, $questionList = array(), $weight = 0) {
  1381. $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1382. $safe_lp_id = intval($safe_lp_id);
  1383. $safe_lp_item_id = intval($safe_lp_item_id);
  1384. $safe_lp_item_view_id = intval($safe_lp_item_view_id);
  1385. if (empty($safe_lp_id)) {
  1386. $safe_lp_id = 0;
  1387. }
  1388. if (empty($safe_lp_item_id)) {
  1389. $safe_lp_item_id = 0;
  1390. }
  1391. if (empty($clock_expired_time)) {
  1392. $clock_expired_time = 0;
  1393. }
  1394. if ($this->expired_time != 0) {
  1395. $sql_fields = "expired_time_control, ";
  1396. $sql_fields_values = "'"."$clock_expired_time"."',";
  1397. } else {
  1398. $sql_fields = "";
  1399. $sql_fields_values = "";
  1400. }
  1401. $questionList = array_map('intval', $questionList);
  1402. $weight = Database::escape_string($weight);
  1403. $sql = "INSERT INTO $track_exercises ($sql_fields exe_exo_id, exe_user_id, exe_cours_id, status,session_id, data_tracking, start_date, orig_lp_id, orig_lp_item_id, exe_weighting)
  1404. VALUES($sql_fields_values '".$this->id."','" . api_get_user_id() . "','" . api_get_course_id() . "','incomplete','" . api_get_session_id() . "','" . implode(',', $questionList) . "', '" . api_get_utc_datetime() . "', '$safe_lp_id', '$safe_lp_item_id', '$weight' )";
  1405. Database::query($sql);
  1406. $id = Database::insert_id();
  1407. return $id;
  1408. }
  1409. public function show_button($question_id, $questionNum, $questions_in_media = array()) {
  1410. global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
  1411. $nbrQuestions = $this->get_count_question_list();
  1412. $all_button = $html = $label = '';
  1413. $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']):null;
  1414. if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {
  1415. $html .= '<a href="exercise_submit_modal.php?learnpath_id='.$safe_lp_id.'&learnpath_item_id='.$safe_lp_item_id.'&learnpath_item_view_id='.$safe_lp_item_view_id.'&origin='.$origin.'&hotspot='.$hotspot_get.'&nbrQuestions='.$nbrQuestions.'&num='.$questionNum.'&exerciseType='.$this->type.'&exerciseId='.$this->id.'&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=480&width=640&modal=true" title="" class="thickbox btn">';
  1416. if ($questionNum == count($this->questionList)) {
  1417. $html .= get_lang('EndTest').'</a>';
  1418. } else {
  1419. $html .= get_lang('ContinueTest').'</a>';
  1420. }
  1421. $html .='<br />';
  1422. } else {
  1423. //User
  1424. if (api_is_allowed_to_session_edit()) {
  1425. if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum) {
  1426. if ($this->review_answers) {
  1427. $label = get_lang('ReviewQuestions');
  1428. $class = 'btn btn-primary';
  1429. } else {
  1430. $label = get_lang('EndTest');
  1431. $class = 'btn btn-success';
  1432. }
  1433. } else {
  1434. $label = get_lang('NextQuestion');
  1435. $class = 'btn btn-primary';
  1436. }
  1437. if ($this->type == ONE_PER_PAGE) {
  1438. if ($questionNum != 1) {
  1439. $prev_question = $questionNum - 2;
  1440. $all_button .= '<a href="javascript://" class="btn" onclick="previous_question_and_save('.$prev_question.', '.$question_id.' ); ">'.get_lang('PreviousQuestion').'</a>';
  1441. }
  1442. if (!empty($questions_in_media)) {
  1443. $questions_in_media = "['".implode("','",$questions_in_media)."']";
  1444. $all_button .= '&nbsp;<a href="javascript://" class="'.$class.'" onclick="save_question_list('.$questions_in_media.'); ">'.$label.'</a>';
  1445. } else {
  1446. $all_button .= '&nbsp;<a href="javascript://" class="'.$class.'" onclick="save_now('.$question_id.'); ">'.$label.'</a>';
  1447. }
  1448. //Next question
  1449. $all_button .= '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span>&nbsp;';
  1450. $html .= $all_button;
  1451. } else {
  1452. if ($this->review_answers) {
  1453. $all_label = get_lang('ReviewQuestions');
  1454. $class = 'btn btn-primary';
  1455. } else {
  1456. $all_label = get_lang('EndTest');
  1457. $class = 'btn btn-success';
  1458. }
  1459. $all_button = '&nbsp;<a href="javascript://" class="'.$class.'" onclick="validate_all(); ">'.$all_label.'</a>';
  1460. $all_button .= '&nbsp;<span id="save_all_reponse"></span>';
  1461. $html .= $all_button;
  1462. }
  1463. }
  1464. }
  1465. return $html;
  1466. }
  1467. /**
  1468. * So the time control will work
  1469. */
  1470. public function show_time_control_js($time_left) {
  1471. $time_left = intval($time_left);
  1472. return "<script>
  1473. function get_expired_date_string(expired_time) {
  1474. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  1475. var day, month, year, hours, minutes, seconds, date_string;
  1476. var obj_date = new Date(expired_time);
  1477. day = obj_date.getDate();
  1478. if (day < 10) day = '0' + day;
  1479. month = obj_date.getMonth();
  1480. year = obj_date.getFullYear();
  1481. hours = obj_date.getHours();
  1482. if (hours < 10) hours = '0' + hours;
  1483. minutes = obj_date.getMinutes();
  1484. if (minutes < 10) minutes = '0' + minutes;
  1485. seconds = obj_date.getSeconds();
  1486. if (seconds < 10) seconds = '0' + seconds;
  1487. date_string = months[month] +' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
  1488. return date_string;
  1489. }
  1490. function open_clock_warning() {
  1491. $('#clock_warning').dialog({
  1492. modal:true,
  1493. height:250,
  1494. closeOnEscape: false,
  1495. resizable: false,
  1496. buttons: {
  1497. '".addslashes(get_lang("EndTest"))."': function() {
  1498. $('#clock_warning').dialog('close');
  1499. },
  1500. },
  1501. close: function() {
  1502. send_form();
  1503. }
  1504. });
  1505. $('#clock_warning').dialog('open');
  1506. $('#counter_to_redirect').epiclock({
  1507. mode: $.epiclock.modes.countdown,
  1508. offset: {seconds: 5},
  1509. format: 's'
  1510. }).bind('timer', function () {
  1511. send_form();
  1512. });
  1513. }
  1514. function send_form() {
  1515. if ($('#exercise_form').length) {
  1516. $('#exercise_form').submit();
  1517. } else {
  1518. //In reminder
  1519. final_submit();
  1520. }
  1521. }
  1522. function onExpiredTimeExercise() {
  1523. $('#wrapper-clock').hide();
  1524. $('#exercise_form').hide();
  1525. $('#expired-message-id').show();
  1526. //Fixes bug #5263
  1527. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  1528. open_clock_warning();
  1529. }
  1530. $(document).ready(function() {
  1531. var current_time = new Date().getTime();
  1532. var time_left = parseInt(".$time_left."); // time in seconds when using minutes there are some seconds lost
  1533. var expired_time = current_time + (time_left*1000);
  1534. var expired_date = get_expired_date_string(expired_time);
  1535. $('#exercise_clock_warning').epiclock({
  1536. mode: $.epiclock.modes.countdown,
  1537. offset: {seconds: time_left},
  1538. format: 'x:i:s',
  1539. renderer: 'minute'
  1540. }).bind('timer', function () {
  1541. onExpiredTimeExercise();
  1542. });
  1543. $('#submit_save').click(function () {});
  1544. });
  1545. </script>";
  1546. }
  1547. /**
  1548. * Lp javascript for hotspots
  1549. */
  1550. public function show_lp_javascript() {
  1551. return "<script type=\"text/javascript\" src=\"../plugin/hotspot/JavaScriptFlashGateway.js\"></script>
  1552. <script src=\"../plugin/hotspot/hotspot.js\" type=\"text/javascript\"></script>
  1553. <script language=\"JavaScript\" type=\"text/javascript\">
  1554. <!--
  1555. // -----------------------------------------------------------------------------
  1556. // Globals
  1557. // Major version of Flash required
  1558. var requiredMajorVersion = 7;
  1559. // Minor version of Flash required
  1560. var requiredMinorVersion = 0;
  1561. // Minor version of Flash required
  1562. var requiredRevision = 0;
  1563. // the version of javascript supported
  1564. var jsVersion = 1.0;
  1565. // -----------------------------------------------------------------------------
  1566. // -->
  1567. </script>
  1568. <script language=\"VBScript\" type=\"text/vbscript\">
  1569. <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
  1570. Function VBGetSwfVer(i)
  1571. on error resume next
  1572. Dim swControl, swVersion
  1573. swVersion = 0
  1574. set swControl = CreateObject(\"ShockwaveFlash.ShockwaveFlash.\" + CStr(i))
  1575. if (IsObject(swControl)) then
  1576. swVersion = swControl.GetVariable(\"\$version\")
  1577. end if
  1578. VBGetSwfVer = swVersion
  1579. End Function
  1580. // -->
  1581. </script>
  1582. <script language=\"JavaScript1.1\" type=\"text/javascript\">
  1583. <!-- // Detect Client Browser type
  1584. var isIE = (navigator.appVersion.indexOf(\"MSIE\") != -1) ? true : false;
  1585. var isWin = (navigator.appVersion.toLowerCase().indexOf(\"win\") != -1) ? true : false;
  1586. var isOpera = (navigator.userAgent.indexOf(\"Opera\") != -1) ? true : false;
  1587. jsVersion = 1.1;
  1588. // JavaScript helper required to detect Flash Player PlugIn version information
  1589. function JSGetSwfVer(i){
  1590. // NS/Opera version >= 3 check for Flash plugin in plugin array
  1591. if (navigator.plugins != null && navigator.plugins.length > 0) {
  1592. if (navigator.plugins[\"Shockwave Flash 2.0\"] || navigator.plugins[\"Shockwave Flash\"]) {
  1593. var swVer2 = navigator.plugins[\"Shockwave Flash 2.0\"] ? \" 2.0\" : \"\";
  1594. var flashDescription = navigator.plugins[\"Shockwave Flash\" + swVer2].description;
  1595. descArray = flashDescription.split(\" \");
  1596. tempArrayMajor = descArray[2].split(\".\");
  1597. versionMajor = tempArrayMajor[0];
  1598. versionMinor = tempArrayMajor[1];
  1599. if ( descArray[3] != \"\" ) {
  1600. tempArrayMinor = descArray[3].split(\"r\");
  1601. } else {
  1602. tempArrayMinor = descArray[4].split(\"r\");
  1603. }
  1604. versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
  1605. flashVer = versionMajor + \".\" + versionMinor + \".\" + versionRevision;
  1606. } else {
  1607. flashVer = -1;
  1608. }
  1609. }
  1610. // MSN/WebTV 2.6 supports Flash 4
  1611. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.6\") != -1) flashVer = 4;
  1612. // WebTV 2.5 supports Flash 3
  1613. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.5\") != -1) flashVer = 3;
  1614. // older WebTV supports Flash 2
  1615. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv\") != -1) flashVer = 2;
  1616. // Can't detect in all other cases
  1617. else {
  1618. flashVer = -1;
  1619. }
  1620. return flashVer;
  1621. }
  1622. // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
  1623. function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
  1624. {
  1625. reqVer = parseFloat(reqMajorVer + \".\" + reqRevision);
  1626. // loop backwards through the versions until we find the newest version
  1627. for (i=25;i>0;i--) {
  1628. if (isIE && isWin && !isOpera) {
  1629. versionStr = VBGetSwfVer(i);
  1630. } else {
  1631. versionStr = JSGetSwfVer(i);
  1632. }
  1633. if (versionStr == -1 ) {
  1634. return false;
  1635. } else if (versionStr != 0) {
  1636. if(isIE && isWin && !isOpera) {
  1637. tempArray = versionStr.split(\" \");
  1638. tempString = tempArray[1];
  1639. versionArray = tempString .split(\",\");
  1640. } else {
  1641. versionArray = versionStr.split(\".\");
  1642. }
  1643. versionMajor = versionArray[0];
  1644. versionMinor = versionArray[1];
  1645. versionRevision = versionArray[2];
  1646. versionString = versionMajor + \".\" + versionRevision; // 7.0r24 == 7.24
  1647. versionNum = parseFloat(versionString);
  1648. // is the major.revision >= requested major.revision AND the minor version >= requested minor
  1649. if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
  1650. return true;
  1651. } else {
  1652. return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
  1653. }
  1654. }
  1655. }
  1656. }
  1657. // -->
  1658. </script>";
  1659. }
  1660. /**
  1661. * This function was originally found in the exercise_show.php
  1662. * @param int exe id
  1663. * @param int question id
  1664. * @param int the choice the user selected
  1665. * @param array the hotspot coordinates $hotspot[$question_id] = coordinates
  1666. * @param string function is called from 'exercise_show' or 'exercise_result'
  1667. * @param bool save results in the DB or just show the reponse
  1668. * @param bool gets information from DB or from the current selection
  1669. * @param bool show results or not
  1670. * @todo reduce parameters of this function
  1671. * @return string html code
  1672. */
  1673. public function manage_answer($exeId, $questionId, $choice, $from = 'exercise_show', $exerciseResultCoordinates = array(), $saved_results = true, $from_database = false, $show_result = true, $propagate_neg = 0, $hotspot_delineation_result = array()) {
  1674. global $feedback_type, $debug;
  1675. global $learnpath_id, $learnpath_item_id; //needed in order to use in the exercise_attempt() for the time
  1676. require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
  1677. if ($debug) error_log("<------ manage_answer ------> ");
  1678. if ($debug) error_log('manage_answer called exe_id: '.$exeId);
  1679. if ($debug) error_log('manage_answer $from: '.$from);
  1680. if ($debug) error_log('manage_answer $saved_results: '.$saved_results);
  1681. if ($debug) error_log('manage_answer $from_database: '.$from_database);
  1682. if ($debug) error_log('manage_answer $show_result: '.$show_result);
  1683. if ($debug) error_log('manage_answer $propagate_neg: '.$propagate_neg);
  1684. if ($debug) error_log('manage_answer $hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
  1685. if ($debug) error_log('manage_answer $learnpath_id: '.$learnpath_id);
  1686. if ($debug) error_log('manage_answer $learnpath_item_id: '.$learnpath_item_id);
  1687. $extra_data = array();
  1688. $arrques = null;
  1689. $arrans = null;
  1690. $questionId = intval($questionId);
  1691. $exeId = intval($exeId);
  1692. $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1693. $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
  1694. // Creates a temporary Question object
  1695. $course_id = api_get_course_int_id();
  1696. $objQuestionTmp = Question::read($questionId, $course_id);
  1697. $questionName = $objQuestionTmp->selectTitle();
  1698. $questionWeighting = $objQuestionTmp->selectWeighting();
  1699. $answerType = $objQuestionTmp->selectType();
  1700. $quesId = $objQuestionTmp->selectId();
  1701. $extra = $objQuestionTmp->extra;
  1702. $next = 1; //not for now
  1703. //Extra information of the question
  1704. if (!empty($extra)) {
  1705. $extra = explode(':', $extra);
  1706. if ($debug) error_log(print_r($extra, 1));
  1707. //Fixes problems with negatives values using intval
  1708. $true_score = intval($extra[0]);
  1709. $false_score = intval($extra[1]);
  1710. $doubt_score = intval($extra[2]);
  1711. }
  1712. $totalWeighting = 0;
  1713. $totalScore = 0;
  1714. // Destruction of the Question object
  1715. unset ($objQuestionTmp);
  1716. // Construction of the Answer object
  1717. $objAnswerTmp = new Answer($questionId);
  1718. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  1719. if ($debug) error_log('Count of answers: '.$nbrAnswers);
  1720. if ($debug) error_log('$answerType: '.$answerType);
  1721. if ($answerType == FREE_ANSWER || $answerType == ORAL_EXPRESSION) {
  1722. $nbrAnswers = 1;
  1723. }
  1724. $nano = null;
  1725. if ($answerType == ORAL_EXPRESSION) {
  1726. require_once api_get_path(LIBRARY_PATH).'nanogong.lib.php';
  1727. $exe_info = get_exercise_results_by_attempt($exeId);
  1728. $exe_info = $exe_info[$exeId];
  1729. $params = array();
  1730. $params['course_id'] = api_get_course_int_id();
  1731. $params['session_id'] = api_get_session_id();
  1732. $params['user_id'] = isset($exe_info['exe_user_id'])? $exe_info['exe_user_id'] : api_get_user_id();
  1733. $params['exercise_id'] = isset($exe_info['exe_exo_id'])? $exe_info['exe_exo_id'] : $this->id;
  1734. $params['question_id'] = $questionId;
  1735. $params['exe_id'] = isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId;
  1736. $nano = new Nanogong($params);
  1737. //probably this attempt came in an exercise all question by page
  1738. if ($feedback_type == 0) {
  1739. $nano->replace_with_real_exe($exeId);
  1740. }
  1741. }
  1742. $user_answer = '';
  1743. // Get answer list for matching
  1744. $sql_answer = 'SELECT id, answer FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id = "'.$questionId.'" ';
  1745. $res_answer = Database::query($sql_answer);
  1746. $answer_matching =array();
  1747. while ($real_answer = Database::fetch_array($res_answer)) {
  1748. $answer_matching[$real_answer['id']]= $real_answer['answer'];
  1749. }
  1750. $real_answers = array();
  1751. $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
  1752. $organs_at_risk_hit = 0;
  1753. $questionScore = 0;
  1754. if ($debug) error_log('Start answer loop ');
  1755. $answer_correct_array = array();
  1756. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  1757. $answer = $objAnswerTmp->selectAnswer($answerId);
  1758. $answerComment = $objAnswerTmp->selectComment($answerId);
  1759. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  1760. $answerWeighting = (float)$objAnswerTmp->selectWeighting($answerId);
  1761. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  1762. $answer_correct_array[$answerId] = (bool)$answerCorrect;
  1763. if ($debug) error_log("answer auto id: $numAnswer ");
  1764. if ($debug) error_log("answer correct : $answerCorrect ");
  1765. //delineation
  1766. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
  1767. $answer_delineation_destination=$objAnswerTmp->selectDestination(1);
  1768. switch ($answerType) {
  1769. // for unique answer
  1770. case UNIQUE_ANSWER :
  1771. case UNIQUE_ANSWER_NO_OPTION :
  1772. if ($from_database) {
  1773. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' and question_id= '".$questionId."'";
  1774. $resultans = Database::query($queryans);
  1775. $choice = Database::result($resultans,0,"answer");
  1776. $studentChoice=($choice == $numAnswer)?1:0;
  1777. if ($studentChoice) {
  1778. $questionScore+=$answerWeighting;
  1779. $totalScore+=$answerWeighting;
  1780. }
  1781. } else {
  1782. $studentChoice=($choice == $numAnswer)?1:0;
  1783. if ($studentChoice) {
  1784. $questionScore+=$answerWeighting;
  1785. $totalScore+=$answerWeighting;
  1786. }
  1787. }
  1788. break;
  1789. // for multiple answers
  1790. case MULTIPLE_ANSWER_TRUE_FALSE :
  1791. if ($from_database) {
  1792. $choice = array();
  1793. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = ".$exeId." and question_id = ".$questionId;
  1794. $resultans = Database::query($queryans);
  1795. while ($row = Database::fetch_array($resultans)) {
  1796. $ind = $row['answer'];
  1797. $result = explode(':',$ind);
  1798. $my_answer_id = $result[0];
  1799. $option = $result[1];
  1800. $choice[$my_answer_id] = $option;
  1801. }
  1802. $studentChoice =$choice[$numAnswer];
  1803. } else {
  1804. $studentChoice =$choice[$numAnswer];
  1805. }
  1806. if (!empty($studentChoice)) {
  1807. if ($studentChoice == $answerCorrect ) {
  1808. $questionScore += $true_score;
  1809. } else {
  1810. if ($quiz_question_options[$studentChoice]['name'] != "Don't know") {
  1811. $questionScore += $false_score;
  1812. } else {
  1813. $questionScore += $doubt_score;
  1814. }
  1815. }
  1816. } else {
  1817. //if no result then the user just hit don't know
  1818. $studentChoice = 3;
  1819. $questionScore += $doubt_score;
  1820. }
  1821. $totalScore = $questionScore;
  1822. break;
  1823. case MULTIPLE_ANSWER : //2
  1824. if ($from_database) {
  1825. $choice = array();
  1826. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  1827. $resultans = Database::query($queryans);
  1828. while ($row = Database::fetch_array($resultans)) {
  1829. $ind = $row['answer'];
  1830. $choice[$ind] = 1;
  1831. }
  1832. $studentChoice = $choice[$numAnswer];
  1833. $real_answers[$answerId] = (bool)$studentChoice;
  1834. if ($studentChoice) {
  1835. $questionScore +=$answerWeighting;
  1836. }
  1837. } else {
  1838. $studentChoice = $choice[$numAnswer];
  1839. $real_answers[$answerId] = (bool)$studentChoice;
  1840. if (isset($studentChoice)) {
  1841. $questionScore += $answerWeighting;
  1842. }
  1843. }
  1844. $totalScore += $answerWeighting;
  1845. if ($debug) error_log("studentChoice: $studentChoice");
  1846. break;
  1847. case GLOBAL_MULTIPLE_ANSWER :
  1848. if ($from_database) {
  1849. $choice = array();
  1850. $queryans = "SELECT answer FROM $TBL_TRACK_ATTEMPT WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  1851. $resultans = Database::query($queryans);
  1852. while ($row = Database::fetch_array($resultans)) {
  1853. $ind = $row['answer'];
  1854. $choice[$ind] = 1;
  1855. }
  1856. $studentChoice = $choice[$numAnswer];
  1857. $real_answers[$answerId] = (bool)$studentChoice;
  1858. if ($studentChoice) {
  1859. $questionScore +=$answerWeighting;
  1860. }
  1861. } else {
  1862. $studentChoice = $choice[$numAnswer];
  1863. if (isset($studentChoice)) {
  1864. $questionScore += $answerWeighting;
  1865. }
  1866. $real_answers[$answerId] = (bool)$studentChoice;
  1867. }
  1868. $totalScore += $answerWeighting;
  1869. if ($debug) error_log("studentChoice: $studentChoice");
  1870. break;
  1871. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  1872. if ($from_database) {
  1873. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = ".$exeId." AND question_id= ".$questionId;
  1874. $resultans = Database::query($queryans);
  1875. while ($row = Database::fetch_array($resultans)) {
  1876. $ind = $row['answer'];
  1877. $result = explode(':',$ind);
  1878. $my_answer_id = $result[0];
  1879. $option = $result[1];
  1880. $choice[$my_answer_id] = $option;
  1881. }
  1882. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  1883. $studentChoice = $choice[$numAnswer];
  1884. if ($answerCorrect == $studentChoice) {
  1885. //$answerCorrect = 1;
  1886. $real_answers[$answerId] = true;
  1887. } else {
  1888. //$answerCorrect = 0;
  1889. $real_answers[$answerId] = false;
  1890. }
  1891. } else {
  1892. $studentChoice = $choice[$numAnswer];
  1893. if ($answerCorrect == $studentChoice) {
  1894. //$answerCorrect = 1;
  1895. $real_answers[$answerId] = true;
  1896. } else {
  1897. //$answerCorrect = 0;
  1898. $real_answers[$answerId] = false;
  1899. }
  1900. }
  1901. break;
  1902. case MULTIPLE_ANSWER_COMBINATION:
  1903. if ($from_database) {
  1904. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
  1905. $resultans = Database::query($queryans);
  1906. while ($row = Database::fetch_array($resultans)) {
  1907. $ind = $row['answer'];
  1908. $choice[$ind] = 1;
  1909. }
  1910. $numAnswer=$objAnswerTmp->selectAutoId($answerId);
  1911. $studentChoice=$choice[$numAnswer];
  1912. if ($answerCorrect == 1) {
  1913. if ($studentChoice) {
  1914. $real_answers[$answerId] = true;
  1915. } else {
  1916. $real_answers[$answerId] = false;
  1917. }
  1918. } else {
  1919. if ($studentChoice) {
  1920. $real_answers[$answerId] = false;
  1921. } else {
  1922. $real_answers[$answerId] = true;
  1923. }
  1924. }
  1925. } else {
  1926. $studentChoice=$choice[$numAnswer];
  1927. if ($answerCorrect == 1) {
  1928. if ($studentChoice) {
  1929. $real_answers[$answerId] = true;
  1930. } else {
  1931. $real_answers[$answerId] = false;
  1932. }
  1933. } else {
  1934. if ($studentChoice) {
  1935. $real_answers[$answerId] = false;
  1936. } else {
  1937. $real_answers[$answerId] = true;
  1938. }
  1939. }
  1940. }
  1941. break;
  1942. // for fill in the blanks
  1943. case FILL_IN_BLANKS :
  1944. // the question is encoded like this
  1945. // [A] B [C] D [E] F::10,10,10@1
  1946. // number 1 before the "@" means that is a switchable fill in blank question
  1947. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  1948. // means that is a normal fill blank question
  1949. // first we explode the "::"
  1950. $pre_array = explode('::', $answer);
  1951. // is switchable fill blank or not
  1952. $last = count($pre_array) - 1;
  1953. $is_set_switchable = explode('@', $pre_array[$last]);
  1954. $switchable_answer_set = false;
  1955. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  1956. $switchable_answer_set = true;
  1957. }
  1958. $answer = '';
  1959. for ($k = 0; $k < $last; $k++) {
  1960. $answer .= $pre_array[$k];
  1961. }
  1962. // splits weightings that are joined with a comma
  1963. $answerWeighting = explode(',', $is_set_switchable[0]);
  1964. // we save the answer because it will be modified
  1965. //$temp = $answer;
  1966. $temp = $answer;
  1967. $answer = '';
  1968. $j = 0;
  1969. //initialise answer tags
  1970. $user_tags = $correct_tags = $real_text = array ();
  1971. // the loop will stop at the end of the text
  1972. while (1) {
  1973. // quits the loop if there are no more blanks (detect '[')
  1974. if (($pos = api_strpos($temp, '[')) === false) {
  1975. // adds the end of the text
  1976. $answer = $temp;
  1977. /* // Deprecated code
  1978. // TeX parsing - replacement of texcode tags
  1979. $texstring = api_parse_tex($texstring);
  1980. $answer = str_replace("{texcode}", $texstring, $answer);
  1981. */
  1982. $real_text[] = $answer;
  1983. break; //no more "blanks", quit the loop
  1984. }
  1985. // adds the piece of text that is before the blank
  1986. //and ends with '[' into a general storage array
  1987. $real_text[] = api_substr($temp, 0, $pos +1);
  1988. $answer .= api_substr($temp, 0, $pos +1);
  1989. //take the string remaining (after the last "[" we found)
  1990. $temp = api_substr($temp, $pos +1);
  1991. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  1992. if (($pos = api_strpos($temp, ']')) === false) {
  1993. // adds the end of the text
  1994. $answer .= $temp;
  1995. break;
  1996. }
  1997. if ($from_database) {
  1998. $queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".Database::escape_string($questionId)."'";
  1999. $resfill = Database::query($queryfill);
  2000. $str = Database::result($resfill,0,'answer');
  2001. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  2002. $str = str_replace('\r\n', '', $str);
  2003. $choice = $arr[1];
  2004. $tmp = api_strrpos($choice[$j],' / ');
  2005. $choice[$j] = api_substr($choice[$j],0,$tmp);
  2006. $choice[$j] = trim($choice[$j]);
  2007. //Needed to let characters ' and " to work as part of an answer
  2008. $choice[$j] = stripslashes($choice[$j]);
  2009. } else {
  2010. $choice[$j] = trim($choice[$j]);
  2011. }
  2012. //No idea why we api_strtolower user reponses
  2013. //$user_tags[] = api_strtolower($choice[$j]);
  2014. $user_tags[] = $choice[$j];
  2015. //put the contents of the [] answer tag into correct_tags[]
  2016. //$correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  2017. $correct_tags[] = api_substr($temp, 0, $pos);
  2018. $j++;
  2019. $temp = api_substr($temp, $pos +1);
  2020. }
  2021. $answer = '';
  2022. $real_correct_tags = $correct_tags;
  2023. $chosen_list = array();
  2024. for ($i = 0; $i < count($real_correct_tags); $i++) {
  2025. if ($i == 0) {
  2026. $answer .= $real_text[0];
  2027. }
  2028. if (!$switchable_answer_set) {
  2029. //needed to parse ' and " characters
  2030. $user_tags[$i] = stripslashes($user_tags[$i]);
  2031. if ($correct_tags[$i] == $user_tags[$i]) {
  2032. // gives the related weighting to the student
  2033. $questionScore += $answerWeighting[$i];
  2034. // increments total score
  2035. $totalScore += $answerWeighting[$i];
  2036. // adds the word in green at the end of the string
  2037. $answer .= $correct_tags[$i];
  2038. }
  2039. // else if the word entered by the student IS NOT the same as the one defined by the professor
  2040. elseif (!empty ($user_tags[$i])) {
  2041. // adds the word in red at the end of the string, and strikes it
  2042. $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>';
  2043. } else {
  2044. // adds a tabulation if no word has been typed by the student
  2045. $answer .= '&nbsp;&nbsp;&nbsp;';
  2046. }
  2047. } else {
  2048. // switchable fill in the blanks
  2049. if (in_array($user_tags[$i], $correct_tags)) {
  2050. $chosen_list[] = $user_tags[$i];
  2051. $correct_tags = array_diff($correct_tags, $chosen_list);
  2052. // gives the related weighting to the student
  2053. $questionScore += $answerWeighting[$i];
  2054. // increments total score
  2055. $totalScore += $answerWeighting[$i];
  2056. // adds the word in green at the end of the string
  2057. $answer .= $user_tags[$i];
  2058. }
  2059. elseif (!empty ($user_tags[$i])) {
  2060. // else if the word entered by the student IS NOT the same as the one defined by the professor
  2061. // adds the word in red at the end of the string, and strikes it
  2062. $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>';
  2063. } else {
  2064. // adds a tabulation if no word has been typed by the student
  2065. $answer .= '&nbsp;&nbsp;&nbsp;';
  2066. }
  2067. }
  2068. // adds the correct word, followed by ] to close the blank
  2069. $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
  2070. if (isset ($real_text[$i +1])) {
  2071. $answer .= $real_text[$i +1];
  2072. }
  2073. }
  2074. break;
  2075. // for free answer
  2076. case FREE_ANSWER :
  2077. if ($from_database) {
  2078. $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2079. $resq = Database::query($query);
  2080. $choice = Database::result($resq,0,'answer');
  2081. $choice = str_replace('\r\n', '', $choice);
  2082. $choice = stripslashes($choice);
  2083. $questionScore = Database::result($resq, 0, "marks");
  2084. if ($questionScore == -1) {
  2085. $totalScore+= 0;
  2086. } else {
  2087. $totalScore+= $questionScore;
  2088. }
  2089. $arrques = $questionName;
  2090. $arrans = $choice;
  2091. } else {
  2092. $studentChoice = $choice;
  2093. if ($studentChoice) {
  2094. //Fixing negative puntation see #2193
  2095. $questionScore = 0;
  2096. $totalScore += 0;
  2097. }
  2098. }
  2099. break;
  2100. case ORAL_EXPRESSION :
  2101. if ($from_database) {
  2102. $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2103. $resq = Database::query($query);
  2104. $choice = Database::result($resq,0,'answer');
  2105. $choice = str_replace('\r\n', '', $choice);
  2106. $choice = stripslashes($choice);
  2107. $questionScore = Database::result($resq,0,"marks");
  2108. if ($questionScore==-1) {
  2109. $totalScore+=0;
  2110. } else {
  2111. $totalScore+=$questionScore;
  2112. }
  2113. $arrques = $questionName;
  2114. $arrans = $choice;
  2115. } else {
  2116. $studentChoice = $choice;
  2117. if ($studentChoice) {
  2118. //Fixing negative puntation see #2193
  2119. $questionScore = 0;
  2120. $totalScore += 0;
  2121. }
  2122. }
  2123. break;
  2124. // for matching
  2125. case MATCHING :
  2126. if ($from_database) {
  2127. $sql_answer = 'SELECT id, answer FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct=0';
  2128. $res_answer = Database::query($sql_answer);
  2129. // getting the real answer
  2130. $real_list =array();
  2131. while ($real_answer = Database::fetch_array($res_answer)) {
  2132. $real_list[$real_answer['id']]= $real_answer['answer'];
  2133. }
  2134. $sql_select_answer = 'SELECT id, answer, correct, id_auto FROM '.$table_ans.'
  2135. WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct <> 0 ORDER BY id_auto';
  2136. $res_answers = Database::query($sql_select_answer);
  2137. $questionScore = 0;
  2138. while ($a_answers = Database::fetch_array($res_answers)) {
  2139. $i_answer_id = $a_answers['id']; //3
  2140. $s_answer_label = $a_answers['answer']; // your daddy - your mother
  2141. $i_answer_correct_answer = $a_answers['correct']; //1 - 2
  2142. $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
  2143. $sql_user_answer = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  2144. WHERE exe_id = '$exeId' AND question_id = '$questionId' AND position='$i_answer_id_auto'";
  2145. $res_user_answer = Database::query($sql_user_answer);
  2146. if (Database::num_rows($res_user_answer)>0 ) {
  2147. $s_user_answer = Database::result($res_user_answer,0,0); // rich - good looking
  2148. } else {
  2149. $s_user_answer = 0;
  2150. }
  2151. $i_answerWeighting=$objAnswerTmp->selectWeighting($i_answer_id);
  2152. $user_answer = '';
  2153. if (!empty($s_user_answer)) {
  2154. if ($s_user_answer == $i_answer_correct_answer) {
  2155. $questionScore += $i_answerWeighting;
  2156. $totalScore += $i_answerWeighting;
  2157. $user_answer = '<span>'.$real_list[$i_answer_correct_answer].'</span>';
  2158. } else {
  2159. $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$real_list[$s_user_answer].'</span>';
  2160. }
  2161. }
  2162. if ($show_result) {
  2163. echo '<tr>';
  2164. echo '<td>'.$s_answer_label.'</td><td>'.$user_answer.' <b><span style="color: #008000;">'.$real_list[$i_answer_correct_answer].'</span></b></td>';
  2165. echo '</tr>';
  2166. }
  2167. }
  2168. break(2); //break the switch and the "for" condition
  2169. } else {
  2170. $numAnswer=$objAnswerTmp->selectAutoId($answerId);
  2171. if ($answerCorrect) {
  2172. if ($answerCorrect == $choice[$numAnswer]) {
  2173. $questionScore += $answerWeighting;
  2174. $totalScore += $answerWeighting;
  2175. $user_answer = '<span>'.$answer_matching[$choice[$numAnswer]].'</span>';
  2176. } else {
  2177. $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$answer_matching[$choice[$numAnswer]].'</span>';
  2178. }
  2179. $matching[$numAnswer] = $choice[$numAnswer];
  2180. }
  2181. break;
  2182. }
  2183. // for hotspot with no order
  2184. case HOT_SPOT :
  2185. if ($from_database) {
  2186. if ($show_result) {
  2187. $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  2188. $query = "SELECT hotspot_correct FROM ".$TBL_TRACK_HOTSPOT." WHERE hotspot_exe_id = '".$exeId."' and hotspot_question_id= '".$questionId."' AND hotspot_answer_id='".Database::escape_string($answerId)."'";
  2189. $resq = Database::query($query);
  2190. $studentChoice = Database::result($resq,0,"hotspot_correct");
  2191. }
  2192. } else {
  2193. $studentChoice = $choice[$answerId];
  2194. if ($studentChoice) {
  2195. $questionScore += $answerWeighting;
  2196. $totalScore += $answerWeighting;
  2197. }
  2198. }
  2199. break;
  2200. // @todo never added to chamilo
  2201. //for hotspot with fixed order
  2202. case HOT_SPOT_ORDER :
  2203. $studentChoice = $choice['order'][$answerId];
  2204. if ($studentChoice == $answerId) {
  2205. $questionScore += $answerWeighting;
  2206. $totalScore += $answerWeighting;
  2207. $studentChoice = true;
  2208. } else {
  2209. $studentChoice = false;
  2210. }
  2211. break;
  2212. // for hotspot with delineation
  2213. case HOT_SPOT_DELINEATION :
  2214. if ($from_database) {
  2215. // getting the user answer
  2216. $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  2217. $query = "SELECT hotspot_correct, hotspot_coordinate from ".$TBL_TRACK_HOTSPOT." where hotspot_exe_id = '".$exeId."' and hotspot_question_id= '".$questionId."' AND hotspot_answer_id='1'"; //by default we take 1 because it's a delineation
  2218. $resq = Database::query($query);
  2219. $row = Database::fetch_array($resq,'ASSOC');
  2220. $choice = $row['hotspot_correct'];
  2221. $user_answer = $row['hotspot_coordinate'];
  2222. // THIS is very important otherwise the poly_compile will throw an error!!
  2223. // round-up the coordinates
  2224. $coords = explode('/',$user_answer);
  2225. $user_array = '';
  2226. foreach ($coords as $coord) {
  2227. list($x,$y) = explode(';',$coord);
  2228. $user_array .= round($x).';'.round($y).'/';
  2229. }
  2230. $user_array = substr($user_array,0,-1);
  2231. } else {
  2232. if ($studentChoice) {
  2233. $newquestionList[]=$questionId;
  2234. }
  2235. if ($answerId===1) {
  2236. $studentChoice =$choice[$answerId];
  2237. $questionScore +=$answerWeighting;
  2238. if ($hotspot_delineation_result[1]==1) {
  2239. $totalScore +=$answerWeighting; //adding the total
  2240. }
  2241. }
  2242. }
  2243. $_SESSION['hotspot_coord'][1] = $delineation_cord;
  2244. $_SESSION['hotspot_dest'][1] = $answer_delineation_destination;
  2245. break;
  2246. } // end switch Answertype
  2247. global $origin;
  2248. if ($show_result) {
  2249. if ($debug) error_log('show result '.$show_result);
  2250. if ($from == 'exercise_result') {
  2251. if ($debug) error_log('Showing questions $from '.$from);
  2252. //display answers (if not matching type, or if the answer is correct)
  2253. if ($answerType != MATCHING || $answerCorrect) {
  2254. if (in_array($answerType, array(UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, GLOBAL_MULTIPLE_ANSWER))) {
  2255. if ($origin != 'learnpath') {
  2256. ExerciseShowFunctions::display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,0,0);
  2257. }
  2258. } elseif($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  2259. if ($origin!='learnpath') {
  2260. ExerciseShowFunctions::display_multiple_answer_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,$questionId,0);
  2261. }
  2262. } elseif($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
  2263. if ($origin!='learnpath') {
  2264. ExerciseShowFunctions::display_multiple_answer_combination_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,0,0);
  2265. }
  2266. } elseif($answerType == FILL_IN_BLANKS) {
  2267. if ($origin!='learnpath') {
  2268. ExerciseShowFunctions::display_fill_in_blanks_answer($answer,0,0);
  2269. }
  2270. } elseif($answerType == FREE_ANSWER) {
  2271. if($origin != 'learnpath') {
  2272. ExerciseShowFunctions::display_free_answer($choice, $exeId, $questionId, $questionScore);
  2273. }
  2274. } elseif($answerType == ORAL_EXPRESSION) {
  2275. // to store the details of open questions in an array to be used in mail
  2276. if ($origin != 'learnpath') {
  2277. ExerciseShowFunctions::display_oral_expression_answer($choice, 0, 0, $nano);
  2278. }
  2279. } elseif($answerType == HOT_SPOT) {
  2280. if ($origin != 'learnpath') {
  2281. ExerciseShowFunctions::display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment);
  2282. }
  2283. } elseif($answerType == HOT_SPOT_ORDER) {
  2284. if ($origin != 'learnpath') {
  2285. ExerciseShowFunctions::display_hotspot_order_answer($answerId, $answer, $studentChoice, $answerComment);
  2286. }
  2287. } elseif ($answerType == HOT_SPOT_DELINEATION) {
  2288. $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
  2289. //$_SESSION['exerciseResultCoordinates']=str_replace('/','|',$user_answer);
  2290. //if (!$comes_from_popup) {
  2291. //round-up the coordinates
  2292. $coords = explode('/',$user_answer);
  2293. $user_array = '';
  2294. foreach ($coords as $coord) {
  2295. list($x,$y) = explode(';',$coord);
  2296. $user_array .= round($x).';'.round($y).'/';
  2297. }
  2298. $user_array = substr($user_array,0,-1);
  2299. if ($next) {
  2300. //$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  2301. // Save into db
  2302. /* $sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, hotspot_course_code, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate )
  2303. VALUES ('".Database::escape_string($_user['user_id'])."', '".Database::escape_string($_course['id'])."', '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', '".Database::escape_string($answerId)."', '".Database::escape_string($studentChoice)."', '".Database::escape_string($user_array)."')";
  2304. $result = api_sql_query($sql,__FILE__,__LINE__);*/
  2305. $user_answer = $user_array;
  2306. // we compare only the delineation not the other points
  2307. $answer_question = $_SESSION['hotspot_coord'][1];
  2308. $answerDestination = $_SESSION['hotspot_dest'][1];
  2309. //calculating the area
  2310. $poly_user = convert_coordinates($user_answer,'/');
  2311. $poly_answer = convert_coordinates($answer_question,'|');
  2312. $max_coord = poly_get_max($poly_user,$poly_answer);
  2313. $poly_user_compiled = poly_compile($poly_user,$max_coord);
  2314. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  2315. $poly_results = poly_result($poly_answer_compiled,$poly_user_compiled,$max_coord);
  2316. $overlap = $poly_results['both'];
  2317. $poly_answer_area = $poly_results['s1'];
  2318. $poly_user_area = $poly_results['s2'];
  2319. $missing = $poly_results['s1Only'];
  2320. $excess = $poly_results['s2Only'];
  2321. //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
  2322. if ($debug>0) error_log(__LINE__.' - Polygons results are '.print_r($poly_results,1),0);
  2323. if ($overlap < 1) {
  2324. //shortcut to avoid complicated calculations
  2325. $final_overlap = 0;
  2326. $final_missing = 100;
  2327. $final_excess = 100;
  2328. } else {
  2329. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  2330. $final_overlap = round(((float)$overlap / (float)$poly_answer_area)*100);
  2331. if ($debug>1) error_log(__LINE__.' - Final overlap is '.$final_overlap,0);
  2332. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  2333. $final_missing = 100 - $final_overlap;
  2334. if ($debug>1) {
  2335. error_log(__LINE__.' - Final missing is '.$final_missing,0);
  2336. }
  2337. // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
  2338. $final_excess = round((((float)$poly_user_area-(float)$overlap)/(float)$poly_answer_area)*100);
  2339. if ($debug>1) {
  2340. error_log(__LINE__.' - Final excess is '.$final_excess,0);
  2341. }
  2342. }
  2343. //checking the destination parameters parsing the "@@"
  2344. $destination_items= explode('@@', $answerDestination);
  2345. $threadhold_total = $destination_items[0];
  2346. $threadhold_items=explode(';',$threadhold_total);
  2347. $threadhold1 = $threadhold_items[0]; // overlap
  2348. $threadhold2 = $threadhold_items[1]; // excess
  2349. $threadhold3 = $threadhold_items[2]; //missing
  2350. // if is delineation
  2351. if ($answerId===1) {
  2352. //setting colors
  2353. if ($final_overlap>=$threadhold1) {
  2354. $overlap_color=true; //echo 'a';
  2355. }
  2356. //echo $excess.'-'.$threadhold2;
  2357. if ($final_excess<=$threadhold2) {
  2358. $excess_color=true; //echo 'b';
  2359. }
  2360. //echo '--------'.$missing.'-'.$threadhold3;
  2361. if ($final_missing<=$threadhold3) {
  2362. $missing_color=true; //echo 'c';
  2363. }
  2364. // if pass
  2365. if ($final_overlap>=$threadhold1 && $final_missing<=$threadhold3 && $final_excess<=$threadhold2) {
  2366. $next=1; //go to the oars
  2367. $result_comment=get_lang('Acceptable');
  2368. $final_answer = 1; // do not update with update_exercise_attempt
  2369. } else {
  2370. $next=0;
  2371. $result_comment=get_lang('Unacceptable');
  2372. $comment=$answerDestination=$objAnswerTmp->selectComment(1);
  2373. $answerDestination=$objAnswerTmp->selectDestination(1);
  2374. //checking the destination parameters parsing the "@@"
  2375. $destination_items= explode('@@', $answerDestination);
  2376. }
  2377. } elseif($answerId>1) {
  2378. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  2379. if ($debug>0) {
  2380. error_log(__LINE__.' - answerId is of type noerror',0);
  2381. }
  2382. //type no error shouldn't be treated
  2383. $next = 1;
  2384. continue;
  2385. }
  2386. if ($debug>0) {
  2387. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR',0);
  2388. }
  2389. //check the intersection between the oar and the user
  2390. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  2391. //echo 'official';print_r($x_list);print_r($y_list);
  2392. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  2393. $inter= $result['success'];
  2394. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  2395. $delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  2396. $poly_answer = convert_coordinates($delineation_cord,'|');
  2397. $max_coord = poly_get_max($poly_user,$poly_answer);
  2398. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  2399. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled,$max_coord);
  2400. if ($overlap == false) {
  2401. //all good, no overlap
  2402. $next = 1;
  2403. continue;
  2404. } else {
  2405. if ($debug>0) {
  2406. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit',0);
  2407. }
  2408. $organs_at_risk_hit++;
  2409. //show the feedback
  2410. $next=0;
  2411. $comment=$answerDestination=$objAnswerTmp->selectComment($answerId);
  2412. $answerDestination=$objAnswerTmp->selectDestination($answerId);
  2413. $destination_items= explode('@@', $answerDestination);
  2414. $try_hotspot=$destination_items[1];
  2415. $lp_hotspot=$destination_items[2];
  2416. $select_question_hotspot=$destination_items[3];
  2417. $url_hotspot=$destination_items[4];
  2418. }
  2419. }
  2420. } else { // the first delineation feedback
  2421. if ($debug>0) {
  2422. error_log(__LINE__.' first',0);
  2423. }
  2424. }
  2425. } elseif($answerType==MATCHING) {
  2426. if ($origin != 'learnpath') {
  2427. echo '<tr>';
  2428. echo '<td>'.text_filter($answer_matching[$answerId]).'</td><td>'.text_filter($user_answer).' / <b><span style="color: #008000;">'.text_filter($answer_matching[$answerCorrect]).'</span></b></td>';
  2429. echo '</tr>';
  2430. }
  2431. }
  2432. }
  2433. } else {
  2434. if ($debug) error_log('Showing questions $from '.$from);
  2435. switch($answerType) {
  2436. case UNIQUE_ANSWER :
  2437. case UNIQUE_ANSWER_NO_OPTION:
  2438. case MULTIPLE_ANSWER :
  2439. case GLOBAL_MULTIPLE_ANSWER :
  2440. case MULTIPLE_ANSWER_COMBINATION :
  2441. if ($answerId==1) {
  2442. ExerciseShowFunctions::display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
  2443. } else {
  2444. ExerciseShowFunctions::display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,"");
  2445. }
  2446. break;
  2447. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  2448. if ($answerId==1) {
  2449. ExerciseShowFunctions::display_multiple_answer_combination_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
  2450. } else {
  2451. ExerciseShowFunctions::display_multiple_answer_combination_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,"");
  2452. }
  2453. break;
  2454. case MULTIPLE_ANSWER_TRUE_FALSE :
  2455. if ($answerId==1) {
  2456. ExerciseShowFunctions::display_multiple_answer_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
  2457. } else {
  2458. ExerciseShowFunctions::display_multiple_answer_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId, "");
  2459. }
  2460. break;
  2461. case FILL_IN_BLANKS:
  2462. ExerciseShowFunctions::display_fill_in_blanks_answer($answer,$exeId,$questionId);
  2463. break;
  2464. case FREE_ANSWER:
  2465. echo ExerciseShowFunctions::display_free_answer($choice, $exeId, $questionId, $questionScore);
  2466. break;
  2467. case ORAL_EXPRESSION:
  2468. echo '<tr>
  2469. <td valign="top">'.ExerciseShowFunctions::display_oral_expression_answer($choice, $exeId, $questionId, $nano).'</td>
  2470. </tr>
  2471. </table>';
  2472. break;
  2473. case HOT_SPOT:
  2474. ExerciseShowFunctions::display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment);
  2475. break;
  2476. case HOT_SPOT_DELINEATION:
  2477. $user_answer = $user_array;
  2478. if ($next) {
  2479. //$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  2480. // Save into db
  2481. /* $sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, hotspot_course_code, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate )
  2482. VALUES ('".Database::escape_string($_user['user_id'])."', '".Database::escape_string($_course['id'])."', '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', '".Database::escape_string($answerId)."', '".Database::escape_string($studentChoice)."', '".Database::escape_string($user_array)."')";
  2483. $result = api_sql_query($sql,__FILE__,__LINE__);*/
  2484. $user_answer = $user_array;
  2485. // we compare only the delineation not the other points
  2486. $answer_question = $_SESSION['hotspot_coord'][1];
  2487. $answerDestination = $_SESSION['hotspot_dest'][1];
  2488. //calculating the area
  2489. $poly_user = convert_coordinates($user_answer,'/');
  2490. $poly_answer = convert_coordinates($answer_question,'|');
  2491. $max_coord = poly_get_max($poly_user,$poly_answer);
  2492. $poly_user_compiled = poly_compile($poly_user,$max_coord);
  2493. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  2494. $poly_results = poly_result($poly_answer_compiled,$poly_user_compiled,$max_coord);
  2495. $overlap = $poly_results['both'];
  2496. $poly_answer_area = $poly_results['s1'];
  2497. $poly_user_area = $poly_results['s2'];
  2498. $missing = $poly_results['s1Only'];
  2499. $excess = $poly_results['s2Only'];
  2500. //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
  2501. if ($debug>0) {
  2502. error_log(__LINE__.' - Polygons results are '.print_r($poly_results,1),0);
  2503. }
  2504. if ($overlap < 1) {
  2505. //shortcut to avoid complicated calculations
  2506. $final_overlap = 0;
  2507. $final_missing = 100;
  2508. $final_excess = 100;
  2509. } else {
  2510. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  2511. $final_overlap = round(((float)$overlap / (float)$poly_answer_area)*100);
  2512. if ($debug>1) {
  2513. error_log(__LINE__.' - Final overlap is '.$final_overlap,0);
  2514. }
  2515. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  2516. $final_missing = 100 - $final_overlap;
  2517. if ($debug>1) {
  2518. error_log(__LINE__.' - Final missing is '.$final_missing,0);
  2519. }
  2520. // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
  2521. $final_excess = round((((float)$poly_user_area-(float)$overlap)/(float)$poly_answer_area)*100);
  2522. if ($debug>1) {
  2523. error_log(__LINE__.' - Final excess is '.$final_excess,0);
  2524. }
  2525. }
  2526. //checking the destination parameters parsing the "@@"
  2527. $destination_items= explode('@@', $answerDestination);
  2528. $threadhold_total = $destination_items[0];
  2529. $threadhold_items=explode(';',$threadhold_total);
  2530. $threadhold1 = $threadhold_items[0]; // overlap
  2531. $threadhold2 = $threadhold_items[1]; // excess
  2532. $threadhold3 = $threadhold_items[2]; //missing
  2533. // if is delineation
  2534. if ($answerId===1) {
  2535. //setting colors
  2536. if ($final_overlap>=$threadhold1) {
  2537. $overlap_color=true; //echo 'a';
  2538. }
  2539. //echo $excess.'-'.$threadhold2;
  2540. if ($final_excess<=$threadhold2) {
  2541. $excess_color=true; //echo 'b';
  2542. }
  2543. //echo '--------'.$missing.'-'.$threadhold3;
  2544. if ($final_missing<=$threadhold3) {
  2545. $missing_color=true; //echo 'c';
  2546. }
  2547. // if pass
  2548. if ($final_overlap>=$threadhold1 && $final_missing<=$threadhold3 && $final_excess<=$threadhold2) {
  2549. $next=1; //go to the oars
  2550. $result_comment=get_lang('Acceptable');
  2551. $final_answer = 1; // do not update with update_exercise_attempt
  2552. } else {
  2553. $next=0;
  2554. $result_comment=get_lang('Unacceptable');
  2555. $comment=$answerDestination=$objAnswerTmp->selectComment(1);
  2556. $answerDestination=$objAnswerTmp->selectDestination(1);
  2557. //checking the destination parameters parsing the "@@"
  2558. $destination_items= explode('@@', $answerDestination);
  2559. }
  2560. } elseif($answerId>1) {
  2561. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  2562. if ($debug>0) {
  2563. error_log(__LINE__.' - answerId is of type noerror',0);
  2564. }
  2565. //type no error shouldn't be treated
  2566. $next = 1;
  2567. continue;
  2568. }
  2569. if ($debug>0) {
  2570. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR',0);
  2571. }
  2572. //check the intersection between the oar and the user
  2573. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  2574. //echo 'official';print_r($x_list);print_r($y_list);
  2575. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  2576. $inter= $result['success'];
  2577. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  2578. $delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  2579. $poly_answer = convert_coordinates($delineation_cord,'|');
  2580. $max_coord = poly_get_max($poly_user,$poly_answer);
  2581. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  2582. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled,$max_coord);
  2583. if ($overlap == false) {
  2584. //all good, no overlap
  2585. $next = 1;
  2586. continue;
  2587. } else {
  2588. if ($debug>0) {
  2589. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit',0);
  2590. }
  2591. $organs_at_risk_hit++;
  2592. //show the feedback
  2593. $next=0;
  2594. $comment=$answerDestination=$objAnswerTmp->selectComment($answerId);
  2595. $answerDestination=$objAnswerTmp->selectDestination($answerId);
  2596. $destination_items= explode('@@', $answerDestination);
  2597. $try_hotspot=$destination_items[1];
  2598. $lp_hotspot=$destination_items[2];
  2599. $select_question_hotspot=$destination_items[3];
  2600. $url_hotspot=$destination_items[4];
  2601. }
  2602. }
  2603. } else { // the first delineation feedback
  2604. if ($debug>0) {
  2605. error_log(__LINE__.' first',0);
  2606. }
  2607. }
  2608. break;
  2609. case HOT_SPOT_ORDER:
  2610. ExerciseShowFunctions::display_hotspot_order_answer($answerId, $answer, $studentChoice, $answerComment);
  2611. break;
  2612. case MATCHING:
  2613. if ($origin != 'learnpath') {
  2614. echo '<tr>';
  2615. echo '<td>'.text_filter($answer_matching[$answerId]).'</td><td>'.text_filter($user_answer).' / <b><span style="color: #008000;">'.text_filter($answer_matching[$answerCorrect]).'</span></b></td>';
  2616. echo '</tr>';
  2617. }
  2618. break;
  2619. }
  2620. }
  2621. }
  2622. if ($debug) error_log(' ------ ');
  2623. } // end for that loops over all answers of the current question
  2624. if ($debug) error_log('-- end answer loop --');
  2625. // destruction of Answer
  2626. if (!$saved_results && $answerType == HOT_SPOT) {
  2627. $queryfree = "SELECT marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".Database::escape_string($exeId)."' and question_id= '".Database::escape_string($questionId)."'";
  2628. $resfree = Database::query($queryfree);
  2629. $questionScore = Database::result($resfree,0,"marks");
  2630. }
  2631. $final_answer = true;
  2632. foreach ($real_answers as $my_answer) {
  2633. if (!$my_answer) {
  2634. $final_answer = false;
  2635. }
  2636. }
  2637. //we add the total score after dealing with the answers
  2638. if ($answerType == MULTIPLE_ANSWER_COMBINATION || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
  2639. if ($final_answer) {
  2640. //getting only the first score where we save the weight of all the question
  2641. $answerWeighting = $objAnswerTmp->selectWeighting(1);
  2642. $questionScore += $answerWeighting;
  2643. $totalScore += $answerWeighting;
  2644. }
  2645. }
  2646. //Fixes multiple answer question in order to be exact
  2647. if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  2648. //var_dump($answer_correct_array, $real_answers);
  2649. $diff = @array_diff($answer_correct_array, $real_answers);
  2650. //var_dump($diff);
  2651. /*
  2652. * All good answers or nothing works like exact
  2653. $counter = 1;
  2654. $correct_answer = true;
  2655. foreach ($real_answers as $my_answer) {
  2656. if ($debug) error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]);
  2657. if ($my_answer != $answer_correct_array[$counter]) {
  2658. $correct_answer = false;
  2659. break;
  2660. }
  2661. $counter++;
  2662. }*/
  2663. if ($debug) error_log(" answer_correct_array: ".print_r($answer_correct_array, 1)."");
  2664. if ($debug) error_log(" real_answers: ".print_r($real_answers, 1)."");
  2665. //if ($debug) error_log(" correct_answer: ".$correct_answer);
  2666. /*if ($correct_answer == false) {
  2667. $questionScore = 0;
  2668. }*/
  2669. //This makes the result non exact
  2670. if (!empty($diff)) {
  2671. //$questionScore = 0;
  2672. }
  2673. }
  2674. $extra_data = array('final_overlap' => $final_overlap, 'final_missing'=>$final_missing, 'final_excess'=> $final_excess,
  2675. 'overlap_color' => $overlap_color, 'missing_color'=>$missing_color, 'excess_color'=> $excess_color,
  2676. 'threadhold1' => $threadhold1, 'threadhold2'=>$threadhold2, 'threadhold3'=> $threadhold3,
  2677. );
  2678. if ($from == 'exercise_result') {
  2679. // if answer is hotspot. To the difference of exercise_show.php, we use the results from the session (from_db=0)
  2680. // TODO Change this, because it is wrong to show the user some results that haven't been stored in the database yet
  2681. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION ) {
  2682. if ($debug) error_log('$from AND this is a hotspot kind of question ');
  2683. $my_exe_id = 0;
  2684. $from_database = 0;
  2685. if ($answerType == HOT_SPOT_DELINEATION) {
  2686. if (0) {
  2687. if ($overlap_color) {
  2688. $overlap_color='green';
  2689. } else {
  2690. $overlap_color='red';
  2691. }
  2692. if ($missing_color) {
  2693. $missing_color='green';
  2694. } else {
  2695. $missing_color='red';
  2696. }
  2697. if ($excess_color) {
  2698. $excess_color='green';
  2699. } else {
  2700. $excess_color='red';
  2701. }
  2702. if (!is_numeric($final_overlap)) {
  2703. $final_overlap = 0;
  2704. }
  2705. if (!is_numeric($final_missing)) {
  2706. $final_missing = 0;
  2707. }
  2708. if (!is_numeric($final_excess)) {
  2709. $final_excess = 0;
  2710. }
  2711. if ($final_overlap>100) {
  2712. $final_overlap = 100;
  2713. }
  2714. $table_resume='<table class="data_table">
  2715. <tr class="row_odd" >
  2716. <td></td>
  2717. <td ><b>'.get_lang('Requirements').'</b></td>
  2718. <td><b>'.get_lang('YourAnswer').'</b></td>
  2719. </tr>
  2720. <tr class="row_even">
  2721. <td><b>'.get_lang('Overlap').'</b></td>
  2722. <td>'.get_lang('Min').' '.$threadhold1.'</td>
  2723. <td><div style="color:'.$overlap_color.'">'.(($final_overlap < 0)?0:intval($final_overlap)).'</div></td>
  2724. </tr>
  2725. <tr>
  2726. <td><b>'.get_lang('Excess').'</b></td>
  2727. <td>'.get_lang('Max').' '.$threadhold2.'</td>
  2728. <td><div style="color:'.$excess_color.'">'.(($final_excess < 0)?0:intval($final_excess)).'</div></td>
  2729. </tr>
  2730. <tr class="row_even">
  2731. <td><b>'.get_lang('Missing').'</b></td>
  2732. <td>'.get_lang('Max').' '.$threadhold3.'</td>
  2733. <td><div style="color:'.$missing_color.'">'.(($final_missing < 0)?0:intval($final_missing)).'</div></td>
  2734. </tr>
  2735. </table>';
  2736. if ($next==0) {
  2737. $try = $try_hotspot;
  2738. $lp = $lp_hotspot;
  2739. $destinationid= $select_question_hotspot;
  2740. $url=$url_hotspot;
  2741. } else {
  2742. //show if no error
  2743. //echo 'no error';
  2744. $comment=$answerComment=$objAnswerTmp->selectComment($nbrAnswers);
  2745. $answerDestination=$objAnswerTmp->selectDestination($nbrAnswers);
  2746. }
  2747. echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
  2748. <p style="text-align:center">';
  2749. $message='<p>'.get_lang('YourDelineation').'</p>';
  2750. $message.=$table_resume;
  2751. $message.='<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
  2752. if ($organs_at_risk_hit>0) {
  2753. $message.='<p><b>'.get_lang('OARHit').'</b></p>';
  2754. }
  2755. $message.='<p>'.$comment.'</p>';
  2756. echo $message;
  2757. } else {
  2758. echo $hotspot_delineation_result[0]; //prints message
  2759. $from_database = 1; // the hotspot_solution.swf needs this variable
  2760. }
  2761. //save the score attempts
  2762. if (1) {
  2763. $final_answer = $hotspot_delineation_result[1]; //getting the answer 1 or 0 comes from exercise_submit_modal.php
  2764. if ($final_answer == 0) {
  2765. $questionScore = 0;
  2766. }
  2767. exercise_attempt($questionScore, 1, $quesId, $exeId, 0); // we always insert the answer_id 1 = delineation
  2768. //in delineation mode, get the answer from $hotspot_delineation_result[1]
  2769. exercise_attempt_hotspot($exeId,$quesId,1, $hotspot_delineation_result[1], $exerciseResultCoordinates[$quesId]);
  2770. } else {
  2771. if ($final_answer==0) {
  2772. $questionScore = 0;
  2773. $answer=0;
  2774. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0);
  2775. if (is_array($exerciseResultCoordinates[$quesId])) {
  2776. foreach($exerciseResultCoordinates[$quesId] as $idx => $val) {
  2777. exercise_attempt_hotspot($exeId,$quesId,$idx,0,$val);
  2778. }
  2779. }
  2780. } else {
  2781. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0);
  2782. if (is_array($exerciseResultCoordinates[$quesId])) {
  2783. foreach($exerciseResultCoordinates[$quesId] as $idx => $val) {
  2784. exercise_attempt_hotspot($exeId,$quesId,$idx,$choice[$idx],$val);
  2785. }
  2786. }
  2787. }
  2788. }
  2789. $my_exe_id = $exeId;
  2790. }
  2791. }
  2792. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
  2793. // We made an extra table for the answers
  2794. if ($show_result) {
  2795. if ($origin != 'learnpath') {
  2796. echo '</table></td></tr>';
  2797. echo '<tr>
  2798. <td colspan="2">';
  2799. echo '<i>'.get_lang('HotSpot').'</i><br /><br />';
  2800. echo '<object type="application/x-shockwave-flash" data="'.api_get_path(WEB_CODE_PATH).'plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id='.$exeId.'&from_db=1" width="552" height="352">
  2801. <param name="movie" value="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id='.$exeId.'&from_db=1" />
  2802. </object>';
  2803. echo '</td>
  2804. </tr>';
  2805. }
  2806. }
  2807. }
  2808. if ($origin != 'learnpath') {
  2809. if ($show_result) {
  2810. echo '</table>';
  2811. }
  2812. }
  2813. }
  2814. unset ($objAnswerTmp);
  2815. $i++;
  2816. $totalWeighting += $questionWeighting;
  2817. // Store results directly in the database
  2818. // For all in one page exercises, the results will be
  2819. // stored by exercise_results.php (using the session)
  2820. if ($saved_results) {
  2821. if ($debug) error_log("Save question results $saved_results");
  2822. if ($debug) error_log(print_r($choice ,1 ));
  2823. if (empty($choice)) {
  2824. $choice = 0;
  2825. }
  2826. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
  2827. if ($choice != 0) {
  2828. $reply = array_keys($choice);
  2829. for ($i = 0; $i < sizeof($reply); $i++) {
  2830. $ans = $reply[$i];
  2831. exercise_attempt($questionScore, $ans.':'.$choice[$ans], $quesId, $exeId, $i, $this->id);
  2832. if ($debug) error_log('result =>'.$questionScore.' '.$ans.':'.$choice[$ans]);
  2833. }
  2834. } else {
  2835. exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  2836. }
  2837. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  2838. if ($choice != 0) {
  2839. $reply = array_keys($choice);
  2840. if ($debug) error_log("reply ".print_r($reply, 1)."");
  2841. for ($i = 0; $i < sizeof($reply); $i++) {
  2842. $ans = $reply[$i];
  2843. exercise_attempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  2844. }
  2845. } else {
  2846. exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  2847. }
  2848. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  2849. if ($choice != 0) {
  2850. $reply = array_keys($choice);
  2851. for ($i = 0; $i < sizeof($reply); $i++) {
  2852. $ans = $reply[$i];
  2853. exercise_attempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  2854. }
  2855. } else {
  2856. exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  2857. }
  2858. } elseif ($answerType == MATCHING) {
  2859. foreach ($matching as $j => $val) {
  2860. exercise_attempt($questionScore, $val, $quesId, $exeId, $j, $this->id);
  2861. }
  2862. } elseif ($answerType == FREE_ANSWER) {
  2863. $answer = $choice;
  2864. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  2865. } elseif ($answerType == ORAL_EXPRESSION) {
  2866. $answer = $choice;
  2867. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $nano);
  2868. } elseif ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) {
  2869. $answer = $choice;
  2870. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  2871. // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  2872. } elseif ($answerType == HOT_SPOT) {
  2873. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  2874. if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
  2875. foreach($exerciseResultCoordinates[$questionId] as $idx => $val) {
  2876. exercise_attempt_hotspot($exeId,$quesId,$idx,$choice[$idx],$val,$this->id);
  2877. }
  2878. }
  2879. } else {
  2880. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0,$this->id);
  2881. }
  2882. }
  2883. if ($propagate_neg == 0 && $questionScore < 0) {
  2884. $questionScore = 0;
  2885. }
  2886. if ($saved_results) {
  2887. $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  2888. $sql_update = 'UPDATE ' . $stat_table . ' SET exe_result = exe_result + ' . floatval($questionScore) . ' WHERE exe_id = ' . $exeId;
  2889. if ($debug) error_log($sql_update);
  2890. Database::query($sql_update);
  2891. }
  2892. $return_array = array( 'score' => $questionScore,
  2893. 'weight' => $questionWeighting,
  2894. 'extra' => $extra_data,
  2895. 'open_question' => $arrques,
  2896. 'open_answer' => $arrans
  2897. );
  2898. return $return_array;
  2899. } //End function
  2900. /**
  2901. * Sends a notification when a user ends an examn
  2902. *
  2903. */
  2904. function send_notification_for_open_questions($question_list_answers, $origin, $exe_id) {
  2905. if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1 ) {
  2906. return null;
  2907. }
  2908. // Email configuration settings
  2909. $coursecode = api_get_course_id();
  2910. $course_info = api_get_course_info(api_get_course_id());
  2911. $url_email = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?'.api_get_cidreq().'&id_session='.api_get_session_id().'&id='.$exe_id.'&action=qualify';
  2912. $user_info = UserManager::get_user_info_by_id(api_get_user_id());
  2913. $msg = '<p>'.get_lang('OpenQuestionsAttempted').' :</p>
  2914. <p>'.get_lang('AttemptDetails').' : </p>
  2915. <table class="data_table">
  2916. <tr>
  2917. <td><h3>'.get_lang('CourseName').'</h3></td>
  2918. <td><h3>#course#</h3></td>
  2919. </tr>
  2920. <tr>
  2921. <td>'.get_lang('TestAttempted').'</span></td>
  2922. <td>#exercise#</td>
  2923. </tr>
  2924. <tr>
  2925. <td>'.get_lang('StudentName').'</td>
  2926. <td>#firstName# #lastName#</td>
  2927. </tr>
  2928. <tr>
  2929. <td>'.get_lang('StudentEmail').'</td>
  2930. <td>#mail#</td>
  2931. </tr>
  2932. </table>';
  2933. $open_question_list = null;
  2934. foreach ($question_list_answers as $item) {
  2935. $question = $item['question'];
  2936. $answer = $item['answer'];
  2937. if (!empty($question) && !empty($answer)) {
  2938. $open_question_list.='<tr>
  2939. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
  2940. <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
  2941. </tr>
  2942. <tr>
  2943. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
  2944. <td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>
  2945. </tr>';
  2946. }
  2947. }
  2948. if (!empty($open_question_list)) {
  2949. $msg .= '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>
  2950. <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
  2951. $msg .= $open_question_list;
  2952. $msg.='</table><br />';
  2953. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  2954. $msg = str_replace("#firstName#", $user_info['firstname'],$msg1);
  2955. $msg1 = str_replace("#lastName#", $user_info['lastname'],$msg);
  2956. $msg = str_replace("#mail#", $user_info['email'],$msg1);
  2957. $msg = str_replace("#course#", $course_info['name'],$msg1);
  2958. if ($origin != 'learnpath') {
  2959. $msg.= get_lang('ClickToCommentAndGiveFeedback').', <br />
  2960. <a href="#url#">#url#</a>';
  2961. }
  2962. $msg1 = str_replace("#url#", $url_email, $msg);
  2963. $mail_content = $msg1;
  2964. $subject = get_lang('OpenQuestionsAttempted');
  2965. $teachers = array();
  2966. if (api_get_session_id()) {
  2967. $teachers = CourseManager::get_coach_list_from_course_code($coursecode, api_get_session_id());
  2968. } else {
  2969. $teachers = CourseManager::get_teacher_list_from_course_code($coursecode);
  2970. }
  2971. if (!empty($teachers)) {
  2972. foreach ($teachers as $user_id => $teacher_data) {
  2973. MessageManager::send_message_simple($user_id, $subject, $mail_content);
  2974. }
  2975. }
  2976. }
  2977. }
  2978. function show_exercise_result_header($user_data, $date = null) {
  2979. $array = array();
  2980. if (!empty($user_data)) {
  2981. $array[] = array('title' => get_lang("User"), 'content' => $user_data);
  2982. }
  2983. if (!empty($this->description)) {
  2984. $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
  2985. }
  2986. if (!empty($date)) {
  2987. $array[] = array('title' => get_lang("Date"), 'content' => $date);
  2988. }
  2989. $html = Display::page_header(Display::return_icon('quiz_big.png', get_lang('Result')).' '.$this->exercise.' : '.get_lang('Result'));
  2990. $html .= Display::description($array);
  2991. return $html;
  2992. }
  2993. /**
  2994. * Create a quiz from quiz data
  2995. * @param string Title
  2996. * @param int Time before it expires (in minutes)
  2997. * @param int Type of exercise
  2998. * @param int Whether it's randomly picked questions (1) or not (0)
  2999. * @param int Whether the exercise is visible to the user (1) or not (0)
  3000. * @param int Whether the results are show to the user (0) or not (1)
  3001. * @param int Maximum number of attempts (0 if no limit)
  3002. * @param int Feedback type
  3003. * @todo this was function was added due the import exercise via CSV
  3004. * @return int New exercise ID
  3005. */
  3006. function create_quiz ($title, $expired_time = 0, $type = 2, $random = 0, $active = 1, $results_disabled = 0, $max_attempt = 0, $feedback = 3) {
  3007. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  3008. $expired_time = filter_var($expired_time,FILTER_SANITIZE_NUMBER_INT);
  3009. $type = filter_var($type,FILTER_SANITIZE_NUMBER_INT);
  3010. $random = filter_var($random,FILTER_SANITIZE_NUMBER_INT);
  3011. $active = filter_var($active,FILTER_SANITIZE_NUMBER_INT);
  3012. $results_disabled = filter_var($results_disabled,FILTER_SANITIZE_NUMBER_INT);
  3013. $max_attempt = filter_var($max_attempt,FILTER_SANITIZE_NUMBER_INT);
  3014. $feedback = filter_var($feedback,FILTER_SANITIZE_NUMBER_INT);
  3015. $sid = api_get_session_id();
  3016. $course_id = api_get_course_int_id();
  3017. // Save a new quiz
  3018. $sql = "INSERT INTO $tbl_quiz (c_id, title,type,random,active,results_disabled, max_attempt,start_time,end_time,feedback_type,expired_time, session_id) ".
  3019. " VALUES('$course_id', '".Database::escape_string($title)."',$type,$random,$active, $results_disabled,$max_attempt,'','',$feedback,$expired_time,$sid)";
  3020. $rs = Database::query($sql);
  3021. $quiz_id = Database::get_last_insert_id();
  3022. return $quiz_id;
  3023. }
  3024. function process_geometry() {
  3025. }
  3026. /**
  3027. * Returns the exercise result
  3028. * @param int attempt id
  3029. * @return float exercise result
  3030. */
  3031. public function get_exercise_result($exe_id) {
  3032. $result = array();
  3033. $track_exercise_info = get_exercise_track_exercise_info($exe_id);
  3034. if (!empty($track_exercise_info)) {
  3035. $objExercise = new Exercise();
  3036. $objExercise->read($track_exercise_info['exe_exo_id']);
  3037. if (!empty($track_exercise_info['data_tracking'])) {
  3038. $question_list = explode(',', $track_exercise_info['data_tracking']);
  3039. }
  3040. foreach ($question_list as $questionId) {
  3041. $question_result = $objExercise->manage_answer($exe_id, $questionId, '','exercise_show', array(), false, true, false, $objExercise->selectPropagateNeg());
  3042. $questionScore = $question_result['score'];
  3043. $totalScore += $question_result['score'];
  3044. }
  3045. if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
  3046. $totalScore = 0;
  3047. }
  3048. $result = array(
  3049. 'score' => $totalScore,
  3050. 'weight' => $track_exercise_info['exe_weighting']
  3051. );
  3052. }
  3053. return $result;
  3054. }
  3055. /**
  3056. * Checks if the exercise is visible due a lot of conditions - visibility, time limits, student attempts
  3057. * @return bool true if is active
  3058. */
  3059. public function is_visible($lp_id = 0, $lp_item_id = 0 , $lp_item_view_id = 0, $filter_by_admin = true) {
  3060. //1. By default the exercise is visible
  3061. $is_visible = true;
  3062. //1.1 Admins and teachers can access to the exercise
  3063. if ($filter_by_admin) {
  3064. if (api_is_platform_admin() || api_is_course_admin()) {
  3065. return array('value' => true, 'message' => '');
  3066. }
  3067. }
  3068. //Checking visibility in the item_property table
  3069. $visibility = api_get_item_visibility(api_get_course_info(), TOOL_QUIZ, $this->id, api_get_session_id());
  3070. if ($visibility == 0) {
  3071. $this->active = 0;
  3072. }
  3073. //2. If the exercise is not active
  3074. if (empty($lp_id)) {
  3075. //2.1 LP is OFF
  3076. if ($this->active == 0) {
  3077. return array('value' => false, 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false));
  3078. }
  3079. } else {
  3080. //2.1 LP is loaded
  3081. if ($this->active == 0 AND !learnpath::is_lp_visible_for_student($lp_id, api_get_user_id())) {
  3082. return array('value' => false, 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false));
  3083. }
  3084. }
  3085. //3. We check if the time limits are on
  3086. $limit_time_exists = ((!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') || (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00')) ? true : false;
  3087. if ($limit_time_exists) {
  3088. $time_now = time();
  3089. if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
  3090. $is_visible = (($time_now - api_strtotime($this->start_time, 'UTC')) > 0) ? true : false;
  3091. }
  3092. if ($is_visible == false) {
  3093. $message = sprintf(get_lang('ExerciseAvailableFromX'), api_convert_and_format_date($this->start_time));
  3094. }
  3095. if ($is_visible == true) {
  3096. if ($this->end_time != '0000-00-00 00:00:00') {
  3097. $is_visible = ((api_strtotime($this->end_time, 'UTC') > $time_now) > 0) ? true : false;
  3098. if ($is_visible == false) {
  3099. $message = sprintf(get_lang('ExerciseAvailableUntilX'), api_convert_and_format_date($this->end_time));
  3100. }
  3101. }
  3102. }
  3103. if ($is_visible == false && $this->start_time != '0000-00-00 00:00:00' && $this->end_time != '0000-00-00 00:00:00') {
  3104. $message = sprintf(get_lang('ExerciseWillBeActivatedFromXToY'), api_convert_and_format_date($this->start_time), api_convert_and_format_date($this->end_time));
  3105. }
  3106. }
  3107. // 4. We check if the student have attempts
  3108. if ($is_visible) {
  3109. if ($this->selectAttempts() > 0) {
  3110. $attempt_count = get_attempt_count_not_finished(api_get_user_id(), $this->id, $lp_id, $lp_item_id, $lp_item_view_id);
  3111. if ($attempt_count >= $this->selectAttempts()) {
  3112. $message = sprintf(get_lang('ReachedMaxAttempts'), $this->name, $this->selectAttempts());
  3113. $is_visible = false;
  3114. }
  3115. }
  3116. }
  3117. if (!empty($message)){
  3118. $message = Display :: return_message($message, 'warning', false);
  3119. }
  3120. return array('value' => $is_visible, 'message' => $message);
  3121. }
  3122. function added_in_lp() {
  3123. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  3124. $sql = "SELECT max_score FROM $TBL_LP_ITEM WHERE c_id = ".$this->course_id." AND item_type = '".TOOL_QUIZ."' AND path = '".$this->id."'";
  3125. $result = Database::query($sql);
  3126. if (Database::num_rows($result) > 0) {
  3127. return true;
  3128. }
  3129. return false;
  3130. }
  3131. function get_media_list() {
  3132. $media_questions = array();
  3133. $question_list = $this->get_validated_question_list();
  3134. if (!empty($question_list)) {
  3135. foreach ($question_list as $questionId) {
  3136. $objQuestionTmp = Question::read($questionId);
  3137. if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
  3138. $media_questions[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
  3139. } else {
  3140. //Always the last item
  3141. $media_questions[999][] = $objQuestionTmp->id;
  3142. }
  3143. }
  3144. }
  3145. return $media_questions;
  3146. }
  3147. /*function get_count_questions_when_using_medias() {
  3148. $media_questions = $this->get_media_list();
  3149. $questions_with_no_group = isset($media_questions[999]) ? count($media_questions[999]) : 0;
  3150. return count($media_questions) - 1 + $questions_with_no_group;
  3151. }*/
  3152. function media_is_activated($media_list) {
  3153. $active = false;
  3154. if (isset($media_list) && !empty($media_list)) {
  3155. $media_count = count($media_list);
  3156. if ($media_count > 1) {
  3157. return true;
  3158. } elseif ($media_count == 1) {
  3159. if (isset($media_list[999])) {
  3160. return false;
  3161. } else {
  3162. return true;
  3163. }
  3164. }
  3165. }
  3166. return $active;
  3167. }
  3168. function get_validated_question_list() {
  3169. $question_list = array();
  3170. $is_random_by_category = $this->isRandomByCat();
  3171. if ($is_random_by_category == 0) {
  3172. if ($this->isRandom()) {
  3173. $question_list = $this->selectRandomList();
  3174. } else {
  3175. $question_list = $this->selectQuestionList();
  3176. }
  3177. } else {
  3178. if ($this->isRandom()) {
  3179. // USE question categories
  3180. /* Get questions by category for this exercice
  3181. we have to choice $objExercise->random question in each array values of $questions_in_category
  3182. key of $tabCategoryQuestions are the categopy id (0 for not in a category)
  3183. value is the array of question id of this category
  3184. */
  3185. $temp_question_list = array();
  3186. //Getting questions by category
  3187. $questions_in_category = Testcategory::getQuestionsByCat($this->id);
  3188. $isRandomByCategory = $this->selectRandomByCat();
  3189. // on tri les catégories en fonction du terme entre [] en tête de la description de la catégorie
  3190. /*
  3191. * ex de catégories :
  3192. * [biologie] Maîtriser les mécanismes de base de la génétique
  3193. * [biologie] Relier les moyens de défenses et les agents infectieux
  3194. * [biologie] Savoir où est produite l'énergie dans les cellules et sous quelle forme
  3195. * [chimie] Classer les molécules suivant leur pouvoir oxydant ou réducteur
  3196. * [chimie] Connaître la définition de la théorie acide/base selon Brönsted
  3197. * [chimie] Connaître les charges des particules
  3198. * On veut dans l'ordre des groupes définis par le terme entre crochet au début du titre de la catégorie
  3199. */
  3200. // If test option is Grouped By Categories
  3201. if ($isRandomByCategory == 2) {
  3202. $questions_in_category = Testcategory::sortTabByBracketLabel($questions_in_category);
  3203. }
  3204. $number_of_random_question = $this->random;
  3205. if ($this->random == -1) {
  3206. $number_of_random_question = count($this->questionList);
  3207. }
  3208. //Only 1 question can have a category
  3209. if (!empty($questions_in_category)) {
  3210. $one_question_per_category = array();
  3211. $questions_added = array();
  3212. foreach ($questions_in_category as $category_id => $question_list) {
  3213. foreach ($question_list as $question_id) {
  3214. if (!in_array($question_id, $questions_added)) {
  3215. $one_question_per_category[$category_id][] = $question_id;
  3216. $questions_added[]= $question_id;
  3217. }
  3218. }
  3219. }
  3220. $questions_in_category = $one_question_per_category;
  3221. }
  3222. //var_dump($questions_in_category);
  3223. while (list($category_id, $question_id) = each($questions_in_category)) {
  3224. $elements = Testcategory::getNElementsFromArray($question_id, $number_of_random_question);
  3225. //var_dump($elements);
  3226. $temp_question_list = array_merge($temp_question_list, $elements);
  3227. }
  3228. // shuffle the question list if test is not grouped by categories
  3229. if ($isRandomByCategory == 1) {
  3230. shuffle($temp_question_list); // or not
  3231. }
  3232. $question_list = $temp_question_list;
  3233. } else {
  3234. // Problem, random by category has been selected and we have no $this->isRandom nnumber of question selected
  3235. // Should not happened
  3236. }
  3237. }
  3238. return $question_list;
  3239. }
  3240. function get_question_list($expand_media_questions = false) {
  3241. $question_list = $this->get_validated_question_list();
  3242. $question_list = $this->transform_question_list_with_medias($question_list, $expand_media_questions);
  3243. return $question_list;
  3244. }
  3245. function transform_question_list_with_medias($question_list, $expand_media_questions = false) {
  3246. $new_question_list = array();
  3247. if (!empty($question_list)) {
  3248. $media_questions = $this->get_media_list();
  3249. $media_active = $this->media_is_activated($media_questions);
  3250. if ($media_active) {
  3251. $counter = 1;
  3252. foreach ($question_list as $question_id) {
  3253. $add_question = true;
  3254. foreach ($media_questions as $media_id => $question_list_in_media) {
  3255. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  3256. $add_question = false;
  3257. if (!in_array($media_id, $new_question_list)) {
  3258. $new_question_list[$counter] = $media_id;
  3259. $counter++;
  3260. }
  3261. break;
  3262. }
  3263. }
  3264. if ($add_question) {
  3265. $new_question_list[$counter] = $question_id;
  3266. $counter++;
  3267. }
  3268. }
  3269. if ($expand_media_questions) {
  3270. $media_key_list = array_keys($media_questions);
  3271. foreach ($new_question_list as &$question_id) {
  3272. if (in_array($question_id, $media_key_list)) {
  3273. $question_id = $media_questions[$question_id];
  3274. }
  3275. }
  3276. $new_question_list = array_flatten($new_question_list);
  3277. }
  3278. } else {
  3279. $new_question_list = $question_list;
  3280. }
  3281. }
  3282. return $new_question_list;
  3283. }
  3284. public function get_stat_track_exercise_info_by_exe_id($exe_id) {
  3285. $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  3286. $exe_id = intval($exe_id);
  3287. $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id ";
  3288. $result = Database::query($sql_track);
  3289. $new_array = array();
  3290. if (Database::num_rows($result) > 0 ) {
  3291. $new_array = Database::fetch_array($result, 'ASSOC');
  3292. $new_array['duration'] = null;
  3293. $start_date = api_get_utc_datetime($new_array['start_date'], true);
  3294. $end_date = api_get_utc_datetime($new_array['exe_date'], true);
  3295. if (!empty($start_date) && !empty($end_date)) {
  3296. $start_date = api_strtotime($start_date, 'UTC');
  3297. $end_date = api_strtotime($end_date, 'UTC');
  3298. if ($start_date && $end_date) {
  3299. $mytime = $end_date- $start_date;
  3300. $time_attemp = learnpathItem :: get_scorm_time('js', $mytime);
  3301. $h = get_lang('h');
  3302. $time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
  3303. $new_array['duration'] = $time_attemp;
  3304. }
  3305. }
  3306. }
  3307. return $new_array;
  3308. }
  3309. public function edit_question_to_remind($exe_id, $question_id, $action = 'add') {
  3310. $exercise_info = self::get_stat_track_exercise_info_by_exe_id($exe_id);
  3311. $question_id = intval($question_id);
  3312. $exe_id = intval($exe_id);
  3313. $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  3314. if ($exercise_info) {
  3315. if (empty($exercise_info['questions_to_check'])) {
  3316. if ($action == 'add') {
  3317. $sql = "UPDATE $track_exercises SET questions_to_check = '$question_id' WHERE exe_id = $exe_id ";
  3318. $result = Database::query($sql);
  3319. }
  3320. } else {
  3321. $remind_list = explode(',',$exercise_info['questions_to_check']);
  3322. $remind_list_string = '';
  3323. if ($action == 'add') {
  3324. if (!in_array($question_id, $remind_list)) {
  3325. $remind_list[] = $question_id;
  3326. if (!empty($remind_list)) {
  3327. sort($remind_list);
  3328. array_filter($remind_list);
  3329. }
  3330. $remind_list_string = implode(',', $remind_list);
  3331. }
  3332. } elseif ($action == 'delete') {
  3333. if (!empty($remind_list)) {
  3334. if (in_array($question_id, $remind_list)) {
  3335. $remind_list = array_flip($remind_list);
  3336. unset($remind_list[$question_id]);
  3337. $remind_list = array_flip($remind_list);
  3338. if (!empty($remind_list)) {
  3339. sort($remind_list);
  3340. array_filter($remind_list);
  3341. $remind_list_string = implode(',', $remind_list);
  3342. }
  3343. }
  3344. }
  3345. }
  3346. $remind_list_string = Database::escape_string($remind_list_string);
  3347. $sql = "UPDATE $track_exercises SET questions_to_check = '$remind_list_string' WHERE exe_id = $exe_id ";
  3348. $result = Database::query($sql);
  3349. }
  3350. }
  3351. }
  3352. public function fill_in_blank_answer_to_array($answer) {
  3353. api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
  3354. $teacher_answer_list = $teacher_answer_list[0];
  3355. return $teacher_answer_list;
  3356. }
  3357. public function fill_in_blank_answer_to_string($answer) {
  3358. $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
  3359. $result = '';
  3360. if (!empty($teacher_answer_list)) {
  3361. $i = 0;
  3362. foreach ($teacher_answer_list as $teacher_item) {
  3363. $value = null;
  3364. //Cleaning student answer list
  3365. $value = strip_tags($teacher_item);
  3366. $value = api_substr($value,1, api_strlen($value)-2);
  3367. $value = explode('/', $value);
  3368. if (!empty($value[0])) {
  3369. $value = trim($value[0]);
  3370. $value = str_replace('&nbsp;', '', $value);
  3371. $result .= $value;
  3372. }
  3373. }
  3374. }
  3375. return $result;
  3376. }
  3377. function return_time_left_div() {
  3378. $html = '<div id="clock_warning" style="display:none">'.Display::return_message(get_lang('ReachedTimeLimit'), 'warning').' '.sprintf(get_lang('YouWillBeRedirectedInXSeconds'), '<span id="counter_to_redirect" class="red_alert"></span>').'</div>';
  3379. $html .= '<div id="exercise_clock_warning" class="well count_down"></div>';
  3380. return $html;
  3381. }
  3382. function get_count_question_list() {
  3383. //Real question count
  3384. $question_count = 0;
  3385. $question_list = $this->get_question_list();
  3386. if (!empty($question_list)) {
  3387. $question_count = count($question_list);
  3388. }
  3389. return $question_count;
  3390. }
  3391. }