exercise.class.php 221 KB

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