exercise.class.php 216 KB

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