exercise.class.php 221 KB

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