exercise.class.php 216 KB

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