exercise.class.php 204 KB

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