exercise.class.php 202 KB

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