exercise.class.php 215 KB

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