exercise.class.php 216 KB

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