exercise.class.php 202 KB

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