exercise.class.php 216 KB

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