exercise.class.php 213 KB

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