exercise.class.php 205 KB

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