exercise.class.php 153 KB

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