exercise.class.php 221 KB

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