exercise.lib.php 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * Class ExerciseLib
  6. * shows a question and its answers
  7. * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
  8. * @author Hubert Borderiou 2011-10-21
  9. * @author ivantcholakov2009-07-20
  10. *
  11. */
  12. class ExerciseLib
  13. {
  14. /**
  15. * Shows a question
  16. *
  17. * @param Exercise $exercise
  18. * @param int $questionId $questionId question id
  19. * @param bool $only_questions if true only show the questions, no exercise title
  20. * @param bool $origin i.e = learnpath
  21. * @param string $current_item current item from the list of questions
  22. * @param bool $show_title
  23. * @param bool $freeze
  24. * @param array $user_choice
  25. * @param bool $show_comment
  26. * @param bool $show_answers
  27. *
  28. * @return bool|int
  29. */
  30. public static function showQuestion(
  31. $exercise,
  32. $questionId,
  33. $only_questions = false,
  34. $origin = false,
  35. $current_item = '',
  36. $show_title = true,
  37. $freeze = false,
  38. $user_choice = array(),
  39. $show_comment = false,
  40. $show_answers = false
  41. ) {
  42. $course_id = empty($exercise->course_id) ? api_get_course_int_id() : $exercise->course_id;
  43. $course = api_get_course_info_by_id($course_id);
  44. // Change false to true in the following line to enable answer hinting
  45. $debug_mark_answer = $show_answers;
  46. // Reads question information
  47. if (!$objQuestionTmp = Question::read($questionId)) {
  48. // Question not found
  49. return false;
  50. }
  51. if ($exercise->feedback_type != EXERCISE_FEEDBACK_TYPE_END) {
  52. $show_comment = false;
  53. }
  54. $answerType = $objQuestionTmp->selectType();
  55. $pictureName = $objQuestionTmp->getPictureFilename();
  56. $s = '';
  57. if ($answerType != HOT_SPOT &&
  58. $answerType != HOT_SPOT_DELINEATION &&
  59. $answerType != ANNOTATION
  60. ) {
  61. // Question is not a hotspot
  62. if (!$only_questions) {
  63. $questionDescription = $objQuestionTmp->selectDescription();
  64. if ($show_title) {
  65. TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
  66. $titleToDisplay = null;
  67. if ($answerType == READING_COMPREHENSION) {
  68. // In READING_COMPREHENSION, the title of the question
  69. // contains the question itself, which can only be
  70. // shown at the end of the given time, so hide for now
  71. $titleToDisplay = Display::div(
  72. $current_item.'. '.get_lang('ReadingComprehension'),
  73. ['class' => 'question_title']
  74. );
  75. } else {
  76. $titleToDisplay = $objQuestionTmp->getTitleToDisplay($current_item);
  77. }
  78. echo $titleToDisplay;
  79. }
  80. if (!empty($questionDescription) && $answerType != READING_COMPREHENSION) {
  81. echo Display::div(
  82. $questionDescription,
  83. array('class' => 'question_description')
  84. );
  85. }
  86. }
  87. if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) &&
  88. $freeze
  89. ) {
  90. return '';
  91. }
  92. echo '<div class="question_options">';
  93. // construction of the Answer object (also gets all answers details)
  94. $objAnswerTmp = new Answer($questionId, api_get_course_int_id(), $exercise);
  95. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  96. $quiz_question_options = Question::readQuestionOption(
  97. $questionId,
  98. $course_id
  99. );
  100. // For "matching" type here, we need something a little bit special
  101. // because the match between the suggestions and the answers cannot be
  102. // done easily (suggestions and answers are in the same table), so we
  103. // have to go through answers first (elems with "correct" value to 0).
  104. $select_items = array();
  105. //This will contain the number of answers on the left side. We call them
  106. // suggestions here, for the sake of comprehensions, while the ones
  107. // on the right side are called answers
  108. $num_suggestions = 0;
  109. if (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) {
  110. if ($answerType == DRAGGABLE) {
  111. $isVertical = $objQuestionTmp->extra == 'v';
  112. $s .= '
  113. <div class="col-md-12 ui-widget ui-helper-clearfix">
  114. <div class="clearfix">
  115. <ul class="exercise-draggable-answer '.($isVertical ? '' : 'list-inline').'"
  116. id="question-'.$questionId.'" data-question="'.$questionId.'">
  117. ';
  118. } else {
  119. $s .= '<div id="drag'.$questionId.'_question" class="drag_question">
  120. <table class="data_table">';
  121. }
  122. // Iterate through answers
  123. $x = 1;
  124. //mark letters for each answer
  125. $letter = 'A';
  126. $answer_matching = array();
  127. $cpt1 = array();
  128. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  129. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  130. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  131. if ($answerCorrect == 0) {
  132. // options (A, B, C, ...) that will be put into the list-box
  133. // have the "correct" field set to 0 because they are answer
  134. $cpt1[$x] = $letter;
  135. $answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId(
  136. $numAnswer
  137. );
  138. $x++;
  139. $letter++;
  140. }
  141. }
  142. $i = 1;
  143. $select_items[0]['id'] = 0;
  144. $select_items[0]['letter'] = '--';
  145. $select_items[0]['answer'] = '';
  146. foreach ($answer_matching as $id => $value) {
  147. $select_items[$i]['id'] = $value['id_auto'];
  148. $select_items[$i]['letter'] = $cpt1[$id];
  149. $select_items[$i]['answer'] = $value['answer'];
  150. $i++;
  151. }
  152. $user_choice_array_position = array();
  153. if (!empty($user_choice)) {
  154. foreach ($user_choice as $item) {
  155. $user_choice_array_position[$item['position']] = $item['answer'];
  156. }
  157. }
  158. $num_suggestions = ($nbrAnswers - $x) + 1;
  159. } elseif ($answerType == FREE_ANSWER) {
  160. $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer'] : null;
  161. $form = new FormValidator('free_choice_'.$questionId);
  162. $config = array(
  163. 'ToolbarSet' => 'TestFreeAnswer'
  164. );
  165. $form->addHtmlEditor(
  166. "choice[".$questionId."]",
  167. null,
  168. false,
  169. false,
  170. $config
  171. );
  172. $form->setDefaults(
  173. array("choice[".$questionId."]" => $fck_content)
  174. );
  175. $s .= $form->returnForm();
  176. } elseif ($answerType == ORAL_EXPRESSION) {
  177. // Add nanog
  178. if (api_get_setting('enable_record_audio') == 'true') {
  179. //@todo pass this as a parameter
  180. global $exercise_stat_info, $exerciseId, $exe_id;
  181. if (!empty($exercise_stat_info)) {
  182. $objQuestionTmp->initFile(
  183. api_get_session_id(),
  184. api_get_user_id(),
  185. $exercise_stat_info['exe_exo_id'],
  186. $exercise_stat_info['exe_id']
  187. );
  188. } else {
  189. $objQuestionTmp->initFile(
  190. api_get_session_id(),
  191. api_get_user_id(),
  192. $exerciseId,
  193. 'temp_exe'
  194. );
  195. }
  196. echo $objQuestionTmp->returnRecorder();
  197. }
  198. $form = new FormValidator('free_choice_'.$questionId);
  199. $config = ['ToolbarSet' => 'TestFreeAnswer'];
  200. //$form->addButtonAdvancedSettings('hide_description_'.$questionId, get_lang('AddDescription'));
  201. $form->addHtml('<div id="'.'hide_description_'.$questionId.'_options" style="display: none;">');
  202. $form->addHtmlEditor(
  203. "choice[".$questionId."]",
  204. null,
  205. false,
  206. false,
  207. $config
  208. );
  209. $form->addHtml('</div>');
  210. $s .= $form->returnForm();
  211. }
  212. // Now navigate through the possible answers, using the max number of
  213. // answers for the question as a limiter
  214. $lines_count = 1; // a counter for matching-type answers
  215. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  216. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  217. ) {
  218. $header = Display::tag('th', get_lang('Options'));
  219. foreach ($objQuestionTmp->options as $item) {
  220. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  221. if (in_array($item, $objQuestionTmp->options)) {
  222. $header .= Display::tag('th', get_lang($item));
  223. } else {
  224. $header .= Display::tag('th', $item);
  225. }
  226. } else {
  227. $header .= Display::tag('th', $item);
  228. }
  229. }
  230. if ($show_comment) {
  231. $header .= Display::tag('th', get_lang('Feedback'));
  232. }
  233. $s .= '<table class="table table-hover table-striped">';
  234. $s .= Display::tag(
  235. 'tr',
  236. $header,
  237. array('style' => 'text-align:left;')
  238. );
  239. }
  240. if ($show_comment) {
  241. if (in_array(
  242. $answerType,
  243. array(
  244. MULTIPLE_ANSWER,
  245. MULTIPLE_ANSWER_COMBINATION,
  246. UNIQUE_ANSWER,
  247. UNIQUE_ANSWER_IMAGE,
  248. UNIQUE_ANSWER_NO_OPTION,
  249. GLOBAL_MULTIPLE_ANSWER,
  250. )
  251. )) {
  252. $header = Display::tag('th', get_lang('Options'));
  253. if ($exercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END) {
  254. $header .= Display::tag('th', get_lang('Feedback'));
  255. }
  256. $s .= '<table class="table table-hover table-striped">';
  257. $s .= Display::tag(
  258. 'tr',
  259. $header,
  260. array('style' => 'text-align:left;')
  261. );
  262. }
  263. }
  264. $matching_correct_answer = 0;
  265. $user_choice_array = array();
  266. if (!empty($user_choice)) {
  267. foreach ($user_choice as $item) {
  268. $user_choice_array[] = $item['answer'];
  269. }
  270. }
  271. $hidingClass = '';
  272. if ($answerType == READING_COMPREHENSION) {
  273. $objQuestionTmp->processText(
  274. $objQuestionTmp->selectDescription()
  275. );
  276. $hidingClass = 'hide-reading-answers';
  277. }
  278. if ($answerType == READING_COMPREHENSION) {
  279. $s .= Display::div(
  280. $objQuestionTmp->selectTitle(),
  281. ['class' => 'question_title '.$hidingClass]
  282. );
  283. }
  284. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  285. $answer = $objAnswerTmp->selectAnswer($answerId);
  286. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  287. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  288. $comment = $objAnswerTmp->selectComment($answerId);
  289. $attributes = array();
  290. switch ($answerType) {
  291. case UNIQUE_ANSWER:
  292. //no break
  293. case UNIQUE_ANSWER_NO_OPTION:
  294. //no break
  295. case UNIQUE_ANSWER_IMAGE:
  296. //no break
  297. case READING_COMPREHENSION:
  298. $input_id = 'choice-'.$questionId.'-'.$answerId;
  299. if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer) {
  300. $attributes = array(
  301. 'id' => $input_id,
  302. 'checked' => 1,
  303. 'selected' => 1
  304. );
  305. } else {
  306. $attributes = array('id' => $input_id);
  307. }
  308. if ($debug_mark_answer) {
  309. if ($answerCorrect) {
  310. $attributes['checked'] = 1;
  311. $attributes['selected'] = 1;
  312. }
  313. }
  314. if ($show_comment) {
  315. $s .= '<tr><td>';
  316. }
  317. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  318. if ($show_comment) {
  319. if (empty($comment)) {
  320. $s .= '<div id="answer'.$questionId.$numAnswer.'" '
  321. . 'class="exercise-unique-answer-image" style="text-align: center">';
  322. } else {
  323. $s .= '<div id="answer'.$questionId.$numAnswer.'" '
  324. . 'class="exercise-unique-answer-image col-xs-6 col-sm-12" style="text-align: center">';
  325. }
  326. } else {
  327. $s .= '<div id="answer'.$questionId.$numAnswer.'" '
  328. . 'class="exercise-unique-answer-image col-xs-6 col-md-3" style="text-align: center">';
  329. }
  330. }
  331. $answer = Security::remove_XSS($answer, STUDENT);
  332. $s .= Display::input(
  333. 'hidden',
  334. 'choice2['.$questionId.']',
  335. '0'
  336. );
  337. $answer_input = null;
  338. $attributes['class'] = 'checkradios';
  339. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  340. $attributes['class'] = '';
  341. $attributes['style'] = 'display: none;';
  342. $answer = '<div class="thumbnail">'.$answer.'</div>';
  343. }
  344. $answer_input .= '<label class="radio '.$hidingClass.'">';
  345. $answer_input .= Display::input(
  346. 'radio',
  347. 'choice['.$questionId.']',
  348. $numAnswer,
  349. $attributes
  350. );
  351. $answer_input .= $answer;
  352. $answer_input .= '</label>';
  353. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  354. $answer_input .= "</div>";
  355. }
  356. if ($show_comment) {
  357. $s .= $answer_input;
  358. $s .= '</td>';
  359. $s .= '<td>';
  360. $s .= $comment;
  361. $s .= '</td>';
  362. $s .= '</tr>';
  363. } else {
  364. $s .= $answer_input;
  365. }
  366. break;
  367. case MULTIPLE_ANSWER:
  368. //no break
  369. case MULTIPLE_ANSWER_TRUE_FALSE:
  370. //no break
  371. case GLOBAL_MULTIPLE_ANSWER:
  372. $input_id = 'choice-'.$questionId.'-'.$answerId;
  373. $answer = Security::remove_XSS($answer, STUDENT);
  374. if (in_array($numAnswer, $user_choice_array)) {
  375. $attributes = array(
  376. 'id' => $input_id,
  377. 'checked' => 1,
  378. 'selected' => 1
  379. );
  380. } else {
  381. $attributes = array('id' => $input_id);
  382. }
  383. if ($debug_mark_answer) {
  384. if ($answerCorrect) {
  385. $attributes['checked'] = 1;
  386. $attributes['selected'] = 1;
  387. }
  388. }
  389. if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  390. $s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
  391. $attributes['class'] = 'checkradios';
  392. $answer_input = '<label class="checkbox">';
  393. $answer_input .= Display::input(
  394. 'checkbox',
  395. 'choice['.$questionId.']['.$numAnswer.']',
  396. $numAnswer,
  397. $attributes
  398. );
  399. $answer_input .= $answer;
  400. $answer_input .= '</label>';
  401. if ($show_comment) {
  402. $s .= '<tr><td>';
  403. $s .= $answer_input;
  404. $s .= '</td>';
  405. $s .= '<td>';
  406. $s .= $comment;
  407. $s .= '</td>';
  408. $s .= '</tr>';
  409. } else {
  410. $s .= $answer_input;
  411. }
  412. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  413. $my_choice = array();
  414. if (!empty($user_choice_array)) {
  415. foreach ($user_choice_array as $item) {
  416. $item = explode(':', $item);
  417. $my_choice[$item[0]] = $item[1];
  418. }
  419. }
  420. $s .= '<tr>';
  421. $s .= Display::tag('td', $answer);
  422. if (!empty($quiz_question_options)) {
  423. foreach ($quiz_question_options as $id => $item) {
  424. if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
  425. $attributes = array(
  426. 'checked' => 1,
  427. 'selected' => 1
  428. );
  429. } else {
  430. $attributes = array();
  431. }
  432. if ($debug_mark_answer) {
  433. if ($id == $answerCorrect) {
  434. $attributes['checked'] = 1;
  435. $attributes['selected'] = 1;
  436. }
  437. }
  438. $s .= Display::tag(
  439. 'td',
  440. Display::input(
  441. 'radio',
  442. 'choice['.$questionId.']['.$numAnswer.']',
  443. $id,
  444. $attributes
  445. ),
  446. array('style' => '')
  447. );
  448. }
  449. }
  450. if ($show_comment) {
  451. $s .= '<td>';
  452. $s .= $comment;
  453. $s .= '</td>';
  454. }
  455. $s .= '</tr>';
  456. }
  457. break;
  458. case MULTIPLE_ANSWER_COMBINATION:
  459. // multiple answers
  460. $input_id = 'choice-'.$questionId.'-'.$answerId;
  461. if (in_array($numAnswer, $user_choice_array)) {
  462. $attributes = array(
  463. 'id' => $input_id,
  464. 'checked' => 1,
  465. 'selected' => 1
  466. );
  467. } else {
  468. $attributes = array('id' => $input_id);
  469. }
  470. if ($debug_mark_answer) {
  471. if ($answerCorrect) {
  472. $attributes['checked'] = 1;
  473. $attributes['selected'] = 1;
  474. }
  475. }
  476. $answer = Security::remove_XSS($answer, STUDENT);
  477. $answer_input = '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
  478. $answer_input .= '<label class="checkbox">';
  479. $answer_input .= Display::input(
  480. 'checkbox',
  481. 'choice['.$questionId.']['.$numAnswer.']',
  482. 1,
  483. $attributes
  484. );
  485. $answer_input .= $answer;
  486. $answer_input .= '</label>';
  487. if ($show_comment) {
  488. $s .= '<tr>';
  489. $s .= '<td>';
  490. $s .= $answer_input;
  491. $s .= '</td>';
  492. $s .= '<td>';
  493. $s .= $comment;
  494. $s .= '</td>';
  495. $s .= '</tr>';
  496. } else {
  497. $s .= $answer_input;
  498. }
  499. break;
  500. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  501. $s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
  502. $my_choice = array();
  503. if (!empty($user_choice_array)) {
  504. foreach ($user_choice_array as $item) {
  505. $item = explode(':', $item);
  506. if (isset($item[1]) && isset($item[0])) {
  507. $my_choice[$item[0]] = $item[1];
  508. }
  509. }
  510. }
  511. $answer = Security::remove_XSS($answer, STUDENT);
  512. $s .= '<tr>';
  513. $s .= Display::tag('td', $answer);
  514. foreach ($objQuestionTmp->options as $key => $item) {
  515. if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
  516. $attributes = array(
  517. 'checked' => 1,
  518. 'selected' => 1
  519. );
  520. } else {
  521. $attributes = array();
  522. }
  523. if ($debug_mark_answer) {
  524. if ($key == $answerCorrect) {
  525. $attributes['checked'] = 1;
  526. $attributes['selected'] = 1;
  527. }
  528. }
  529. $s .= Display::tag(
  530. 'td',
  531. Display::input(
  532. 'radio',
  533. 'choice['.$questionId.']['.$numAnswer.']',
  534. $key,
  535. $attributes
  536. )
  537. );
  538. }
  539. if ($show_comment) {
  540. $s .= '<td>';
  541. $s .= $comment;
  542. $s .= '</td>';
  543. }
  544. $s .= '</tr>';
  545. break;
  546. case FILL_IN_BLANKS:
  547. // display the question, with field empty, for student to fill it,
  548. // or filled to display the answer in the Question preview of the exercise/admin.php page
  549. $displayForStudent = true;
  550. $listAnswerInfo = FillBlanks::getAnswerInfo($answer);
  551. // Correct answers
  552. $correctAnswerList = $listAnswerInfo['tabwords'];
  553. // Student's answer
  554. $studentAnswerList = array();
  555. if (isset($user_choice[0]['answer'])) {
  556. $arrayStudentAnswer = FillBlanks::getAnswerInfo(
  557. $user_choice[0]['answer'],
  558. true
  559. );
  560. $studentAnswerList = $arrayStudentAnswer['studentanswer'];
  561. }
  562. // If the question must be shown with the answer (in page exercise/admin.php) for teacher preview
  563. // set the student-answer to the correct answer
  564. if ($debug_mark_answer) {
  565. $studentAnswerList = $correctAnswerList;
  566. $displayForStudent = false;
  567. }
  568. if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
  569. $answer = '';
  570. for ($i = 0; $i < count($listAnswerInfo['commonwords']) - 1; $i++) {
  571. // display the common word
  572. $answer .= $listAnswerInfo['commonwords'][$i];
  573. // display the blank word
  574. $correctItem = $listAnswerInfo['tabwords'][$i];
  575. if (isset($studentAnswerList[$i])) {
  576. // If student already started this test and answered this question,
  577. // fill the blank with his previous answers
  578. // may be "" if student viewed the question, but did not fill the blanks
  579. $correctItem = $studentAnswerList[$i];
  580. }
  581. $attributes['style'] = "width:".$listAnswerInfo['tabinputsize'][$i]."px";
  582. $answer .= FillBlanks::getFillTheBlankHtml(
  583. $current_item,
  584. $questionId,
  585. $correctItem,
  586. $attributes,
  587. $answer,
  588. $listAnswerInfo,
  589. $displayForStudent,
  590. $i
  591. );
  592. }
  593. // display the last common word
  594. $answer .= $listAnswerInfo['commonwords'][$i];
  595. } else {
  596. // display empty [input] with the right width for student to fill it
  597. $answer = '';
  598. for ($i = 0; $i < count($listAnswerInfo['commonwords']) - 1; $i++) {
  599. // display the common words
  600. $answer .= $listAnswerInfo['commonwords'][$i];
  601. // display the blank word
  602. $attributes["style"] = "width:".$listAnswerInfo['tabinputsize'][$i]."px";
  603. $answer .= FillBlanks::getFillTheBlankHtml(
  604. $current_item,
  605. $questionId,
  606. '',
  607. $attributes,
  608. $answer,
  609. $listAnswerInfo,
  610. $displayForStudent,
  611. $i
  612. );
  613. }
  614. // display the last common word
  615. $answer .= $listAnswerInfo['commonwords'][$i];
  616. }
  617. $s .= $answer;
  618. break;
  619. case CALCULATED_ANSWER:
  620. /*
  621. * In the CALCULATED_ANSWER test
  622. * you mustn't have [ and ] in the textarea
  623. * you mustn't have @@ in the textarea
  624. * the text to find mustn't be empty or contains only spaces
  625. * the text to find mustn't contains HTML tags
  626. * the text to find mustn't contains char "
  627. */
  628. if ($origin !== null) {
  629. global $exe_id;
  630. $trackAttempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  631. $sql = 'SELECT answer FROM '.$trackAttempts.'
  632. WHERE exe_id=' . $exe_id.' AND question_id='.$questionId;
  633. $rsLastAttempt = Database::query($sql);
  634. $rowLastAttempt = Database::fetch_array($rsLastAttempt);
  635. $answer = $rowLastAttempt['answer'];
  636. if (empty($answer)) {
  637. $_SESSION['calculatedAnswerId'][$questionId] = mt_rand(
  638. 1,
  639. $nbrAnswers
  640. );
  641. $answer = $objAnswerTmp->selectAnswer(
  642. $_SESSION['calculatedAnswerId'][$questionId]
  643. );
  644. }
  645. }
  646. list($answer) = explode('@@', $answer);
  647. // $correctAnswerList array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
  648. api_preg_match_all(
  649. '/\[[^]]+\]/',
  650. $answer,
  651. $correctAnswerList
  652. );
  653. // get student answer to display it if student go back to previous calculated answer question in a test
  654. if (isset($user_choice[0]['answer'])) {
  655. api_preg_match_all(
  656. '/\[[^]]+\]/',
  657. $answer,
  658. $studentAnswerList
  659. );
  660. $studentAnswerListTobecleaned = $studentAnswerList[0];
  661. $studentAnswerList = array();
  662. for ($i = 0; $i < count(
  663. $studentAnswerListTobecleaned
  664. ); $i++) {
  665. $answerCorrected = $studentAnswerListTobecleaned[$i];
  666. $answerCorrected = api_preg_replace(
  667. '| / <font color="green"><b>.*$|',
  668. '',
  669. $answerCorrected
  670. );
  671. $answerCorrected = api_preg_replace(
  672. '/^\[/',
  673. '',
  674. $answerCorrected
  675. );
  676. $answerCorrected = api_preg_replace(
  677. '|^<font color="red"><s>|',
  678. '',
  679. $answerCorrected
  680. );
  681. $answerCorrected = api_preg_replace(
  682. '|</s></font>$|',
  683. '',
  684. $answerCorrected
  685. );
  686. $answerCorrected = '['.$answerCorrected.']';
  687. $studentAnswerList[] = $answerCorrected;
  688. }
  689. }
  690. // If display preview of answer in test view for exemple, set the student answer to the correct answers
  691. if ($debug_mark_answer) {
  692. // contain the rights answers surronded with brackets
  693. $studentAnswerList = $correctAnswerList[0];
  694. }
  695. /*
  696. Split the response by bracket
  697. tabComments is an array with text surrounding the text to find
  698. we add a space before and after the answerQuestion to be sure to
  699. have a block of text before and after [xxx] patterns
  700. so we have n text to find ([xxx]) and n+1 block of texts before,
  701. between and after the text to find
  702. */
  703. $tabComments = api_preg_split(
  704. '/\[[^]]+\]/',
  705. ' '.$answer.' '
  706. );
  707. if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
  708. $answer = "";
  709. $i = 0;
  710. foreach ($studentAnswerList as $studentItem) {
  711. // remove surronding brackets
  712. $studentResponse = api_substr(
  713. $studentItem,
  714. 1,
  715. api_strlen($studentItem) - 2
  716. );
  717. $size = strlen($studentItem);
  718. $attributes['class'] = self::detectInputAppropriateClass(
  719. $size
  720. );
  721. $answer .= $tabComments[$i].
  722. Display::input(
  723. 'text',
  724. "choice[$questionId][]",
  725. $studentResponse,
  726. $attributes
  727. );
  728. $i++;
  729. }
  730. $answer .= $tabComments[$i];
  731. } else {
  732. // display exercise with empty input fields
  733. // every [xxx] are replaced with an empty input field
  734. foreach ($correctAnswerList[0] as $item) {
  735. $size = strlen($item);
  736. $attributes['class'] = self::detectInputAppropriateClass(
  737. $size
  738. );
  739. $answer = str_replace(
  740. $item,
  741. Display::input(
  742. 'text',
  743. "choice[$questionId][]",
  744. '',
  745. $attributes
  746. ),
  747. $answer
  748. );
  749. }
  750. }
  751. if ($origin !== null) {
  752. $s = $answer;
  753. break;
  754. } else {
  755. $s .= $answer;
  756. }
  757. break;
  758. case MATCHING:
  759. // matching type, showing suggestions and answers
  760. // TODO: replace $answerId by $numAnswer
  761. if ($answerCorrect != 0) {
  762. // only show elements to be answered (not the contents of
  763. // the select boxes, who are correct = 0)
  764. $s .= '<tr><td width="45%" valign="top">';
  765. $parsed_answer = $answer;
  766. // Left part questions
  767. $s .= '<p class="indent">'.$lines_count.'.&nbsp;'.$parsed_answer.'</p></td>';
  768. // Middle part (matches selects)
  769. // Id of select is # question + # of option
  770. $s .= '<td width="10%" valign="top" align="center">
  771. <div class="select-matching">
  772. <select id="choice_id_'.$current_item.'_'.$lines_count.'" name="choice['.$questionId.']['.$numAnswer.']">';
  773. // fills the list-box
  774. foreach ($select_items as $key => $val) {
  775. // set $debug_mark_answer to true at function start to
  776. // show the correct answer with a suffix '-x'
  777. $selected = '';
  778. if ($debug_mark_answer) {
  779. if ($val['id'] == $answerCorrect) {
  780. $selected = 'selected="selected"';
  781. }
  782. }
  783. //$user_choice_array_position
  784. if (isset($user_choice_array_position[$numAnswer]) &&
  785. $val['id'] == $user_choice_array_position[$numAnswer]
  786. ) {
  787. $selected = 'selected="selected"';
  788. }
  789. $s .= '<option value="'.$val['id'].'" '.$selected.'>'.$val['letter'].'</option>';
  790. } // end foreach()
  791. $s .= '</select></div></td><td width="5%" class="separate">&nbsp;</td>';
  792. $s .= '<td width="40%" valign="top" >';
  793. if (isset($select_items[$lines_count])) {
  794. $s .= '<div class="text-right"><p class="indent">'.$select_items[$lines_count]['letter'].'.&nbsp; '.$select_items[$lines_count]['answer'].'</p></div>';
  795. } else {
  796. $s .= '&nbsp;';
  797. }
  798. $s .= '</td>';
  799. $s .= '</tr>';
  800. $lines_count++;
  801. //if the left side of the "matching" has been completely
  802. // shown but the right side still has values to show...
  803. if (($lines_count - 1) == $num_suggestions) {
  804. // if it remains answers to shown at the right side
  805. while (isset($select_items[$lines_count])) {
  806. $s .= '<tr>
  807. <td colspan="2"></td>
  808. <td valign="top">';
  809. $s .= '<b>'.$select_items[$lines_count]['letter'].'.</b> '.$select_items[$lines_count]['answer'];
  810. $s .= "</td>
  811. </tr>";
  812. $lines_count++;
  813. } // end while()
  814. } // end if()
  815. $matching_correct_answer++;
  816. }
  817. break;
  818. case DRAGGABLE:
  819. if ($answerCorrect) {
  820. $parsed_answer = $answer;
  821. /*$lines_count = '';
  822. $data = $objAnswerTmp->getAnswerByAutoId($numAnswer);
  823. $data = $objAnswerTmp->getAnswerByAutoId($data['correct']);
  824. $lines_count = $data['answer'];*/
  825. $windowId = $questionId.'_'.$lines_count;
  826. $s .= '<li class="touch-items" id="'.$windowId.'">';
  827. $s .= Display::div(
  828. $parsed_answer,
  829. [
  830. 'id' => "window_$windowId",
  831. 'class' => "window{$questionId}_question_draggable exercise-draggable-answer-option"
  832. ]
  833. );
  834. $draggableSelectOptions = [];
  835. $selectedValue = 0;
  836. $selectedIndex = 0;
  837. if ($user_choice) {
  838. foreach ($user_choice as $chosen) {
  839. if ($answerCorrect != $chosen['answer']) {
  840. continue;
  841. }
  842. $selectedValue = $chosen['answer'];
  843. }
  844. }
  845. foreach ($select_items as $key => $select_item) {
  846. $draggableSelectOptions[$select_item['id']] = $select_item['letter'];
  847. }
  848. foreach ($draggableSelectOptions as $value => $text) {
  849. if ($value == $selectedValue) {
  850. break;
  851. }
  852. $selectedIndex++;
  853. }
  854. $s .= Display::select(
  855. "choice[$questionId][$numAnswer]",
  856. $draggableSelectOptions,
  857. $selectedValue,
  858. [
  859. 'id' => "window_{$windowId}_select",
  860. 'class' => 'select_option hidden',
  861. ],
  862. false
  863. );
  864. if ($selectedValue && $selectedIndex) {
  865. $s .= "
  866. <script>
  867. $(function() {
  868. DraggableAnswer.deleteItem(
  869. $('#{$questionId}_$lines_count'),
  870. $('#drop_{$questionId}_{$selectedIndex}')
  871. );
  872. });
  873. </script>
  874. ";
  875. }
  876. if (isset($select_items[$lines_count])) {
  877. $s .= Display::div(
  878. Display::tag(
  879. 'b',
  880. $select_items[$lines_count]['letter']
  881. ).$select_items[$lines_count]['answer'],
  882. [
  883. 'id' => "window_{$windowId}_answer",
  884. 'class' => 'hidden'
  885. ]
  886. );
  887. } else {
  888. $s .= '&nbsp;';
  889. }
  890. $lines_count++;
  891. if (($lines_count - 1) == $num_suggestions) {
  892. while (isset($select_items[$lines_count])) {
  893. $s .= Display::tag('b', $select_items[$lines_count]['letter']);
  894. $s .= $select_items[$lines_count]['answer'];
  895. $lines_count++;
  896. }
  897. }
  898. $matching_correct_answer++;
  899. $s .= '</li>';
  900. }
  901. break;
  902. case MATCHING_DRAGGABLE:
  903. if ($answerId == 1) {
  904. echo $objAnswerTmp->getJs();
  905. }
  906. if ($answerCorrect != 0) {
  907. $parsed_answer = $answer;
  908. $windowId = "{$questionId}_{$lines_count}";
  909. $s .= <<<HTML
  910. <tr>
  911. <td widht="45%">
  912. <div id="window_{$windowId}" class="window window_left_question window{$questionId}_question">
  913. <strong>$lines_count.</strong> $parsed_answer
  914. </div>
  915. </td>
  916. <td width="10%">
  917. HTML;
  918. $draggableSelectOptions = [];
  919. $selectedValue = 0;
  920. $selectedIndex = 0;
  921. if ($user_choice) {
  922. foreach ($user_choice as $chosen) {
  923. if ($answerCorrect != $chosen['answer']) {
  924. continue;
  925. }
  926. $selectedValue = $chosen['answer'];
  927. }
  928. }
  929. foreach ($select_items as $key => $select_item) {
  930. $draggableSelectOptions[$select_item['id']] = $select_item['letter'];
  931. }
  932. foreach ($draggableSelectOptions as $value => $text) {
  933. if ($value == $selectedValue) {
  934. break;
  935. }
  936. $selectedIndex++;
  937. }
  938. $s .= Display::select(
  939. "choice[$questionId][$numAnswer]",
  940. $draggableSelectOptions,
  941. $selectedValue,
  942. [
  943. 'id' => "window_{$windowId}_select",
  944. 'class' => 'hidden'
  945. ],
  946. false
  947. );
  948. if (!empty($answerCorrect) && !empty($selectedValue)) {
  949. // Show connect if is not freeze (question preview)
  950. if (!$freeze) {
  951. $s .= "
  952. <script>
  953. $(document).on('ready', function () {
  954. jsPlumb.ready(function() {
  955. jsPlumb.connect({
  956. source: 'window_$windowId',
  957. target: 'window_{$questionId}_{$selectedIndex}_answer',
  958. endpoint: ['Blank', {radius: 15}],
  959. anchors: ['RightMiddle', 'LeftMiddle'],
  960. paintStyle: {strokeStyle: '#8A8888', lineWidth: 8},
  961. connector: [
  962. MatchingDraggable.connectorType,
  963. {curvines: MatchingDraggable.curviness}
  964. ]
  965. });
  966. });
  967. });
  968. </script>
  969. ";
  970. }
  971. }
  972. $s .= <<<HTML
  973. </td>
  974. <td width="45%">
  975. HTML;
  976. if (isset($select_items[$lines_count])) {
  977. $s .= <<<HTML
  978. <div id="window_{$windowId}_answer" class="window window_right_question">
  979. <strong>{$select_items[$lines_count]['letter']}.</strong> {$select_items[$lines_count]['answer']}
  980. </div>
  981. HTML;
  982. } else {
  983. $s .= '&nbsp;';
  984. }
  985. $s .= '</td></tr>';
  986. $lines_count++;
  987. if (($lines_count - 1) == $num_suggestions) {
  988. while (isset($select_items[$lines_count])) {
  989. $s .= <<<HTML
  990. <tr>
  991. <td colspan="2"></td>
  992. <td>
  993. <strong>{$select_items[$lines_count]['letter']}</strong>
  994. {$select_items[$lines_count]['answer']}
  995. </td>
  996. </tr>
  997. HTML;
  998. $lines_count++;
  999. }
  1000. }
  1001. $matching_correct_answer++;
  1002. }
  1003. break;
  1004. }
  1005. } // end for()
  1006. if ($show_comment) {
  1007. $s .= '</table>';
  1008. } elseif (in_array(
  1009. $answerType,
  1010. [
  1011. MATCHING,
  1012. MATCHING_DRAGGABLE,
  1013. UNIQUE_ANSWER_NO_OPTION,
  1014. MULTIPLE_ANSWER_TRUE_FALSE,
  1015. MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE,
  1016. ]
  1017. )) {
  1018. $s .= '</table>';
  1019. }
  1020. if ($answerType == DRAGGABLE) {
  1021. $isVertical = $objQuestionTmp->extra == 'v';
  1022. $s .= "</ul>";
  1023. $s .= "</div>"; //clearfix
  1024. $counterAnswer = 1;
  1025. $s .= $isVertical ? '' : '<div class="row">';
  1026. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  1027. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  1028. $windowId = $questionId.'_'.$counterAnswer;
  1029. if ($answerCorrect) {
  1030. $s .= $isVertical ? '<div class="row">' : '';
  1031. $s .= '
  1032. <div class="'.($isVertical ? 'col-md-12' : 'col-xs-12 col-sm-4 col-md-3 col-lg-2').'">
  1033. <div id="drop_'.$windowId.'" class="droppable">&nbsp;</div>
  1034. </div>
  1035. ';
  1036. $s .= $isVertical ? '</div>' : '';
  1037. $counterAnswer++;
  1038. }
  1039. }
  1040. $s .= $isVertical ? '' : '</div>'; // row
  1041. $s .= '</div>'; // col-md-12 ui-widget ui-helper-clearfix
  1042. }
  1043. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  1044. $s .= '</div>'; //drag_question
  1045. }
  1046. $s .= '</div>'; //question_options row
  1047. // destruction of the Answer object
  1048. unset($objAnswerTmp);
  1049. // destruction of the Question object
  1050. unset($objQuestionTmp);
  1051. if ($origin == 'export') {
  1052. return $s;
  1053. }
  1054. echo $s;
  1055. } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  1056. global $exerciseId, $exe_id;
  1057. // Question is a HOT_SPOT
  1058. //checking document/images visibility
  1059. if (api_is_platform_admin() || api_is_course_admin()) {
  1060. $doc_id = $objQuestionTmp->getPictureId();
  1061. if (is_numeric($doc_id)) {
  1062. $images_folder_visibility = api_get_item_visibility(
  1063. $course,
  1064. 'document',
  1065. $doc_id,
  1066. api_get_session_id()
  1067. );
  1068. if (!$images_folder_visibility) {
  1069. // Show only to the course/platform admin if the image is set to visibility = false
  1070. echo Display::return_message(
  1071. get_lang('ChangeTheVisibilityOfTheCurrentImage'),
  1072. 'warning'
  1073. );
  1074. }
  1075. }
  1076. }
  1077. $questionName = $objQuestionTmp->selectTitle();
  1078. $questionDescription = $objQuestionTmp->selectDescription();
  1079. // Get the answers, make a list
  1080. $objAnswerTmp = new Answer($questionId);
  1081. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  1082. // get answers of hotpost
  1083. $answers_hotspot = array();
  1084. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  1085. $answers = $objAnswerTmp->selectAnswerByAutoId(
  1086. $objAnswerTmp->selectAutoId($answerId)
  1087. );
  1088. $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer(
  1089. $answerId
  1090. );
  1091. }
  1092. $answerList = '';
  1093. $hotspotColor = 0;
  1094. if ($answerType != HOT_SPOT_DELINEATION) {
  1095. $answerList = '
  1096. <div class="well well-sm">
  1097. <h5 class="page-header">' . get_lang('HotspotZones').'</h5>
  1098. <ol>
  1099. ';
  1100. if (!empty($answers_hotspot)) {
  1101. Session::write("hotspot_ordered$questionId", array_keys($answers_hotspot));
  1102. foreach ($answers_hotspot as $value) {
  1103. $answerList .= "<li>";
  1104. if ($freeze) {
  1105. $answerList .= '<span class="hotspot-color-'.$hotspotColor
  1106. .' fa fa-square" aria-hidden="true"></span>'.PHP_EOL;
  1107. }
  1108. $answerList .= $value;
  1109. $answerList .= "</li>";
  1110. $hotspotColor++;
  1111. }
  1112. }
  1113. $answerList .= '
  1114. </ul>
  1115. </div>
  1116. ';
  1117. if ($freeze) {
  1118. $relPath = api_get_path(WEB_CODE_PATH);
  1119. echo "
  1120. <div class=\"row\">
  1121. <div class=\"col-sm-9\">
  1122. <div id=\"hotspot-preview-$questionId\"></div>
  1123. </div>
  1124. <div class=\"col-sm-3\">
  1125. $answerList
  1126. </div>
  1127. </div>
  1128. <script>
  1129. new ".($answerType == HOT_SPOT ? "HotspotQuestion" : "DelineationQuestion")."({
  1130. questionId: $questionId,
  1131. exerciseId: $exerciseId,
  1132. selector: '#hotspot-preview-$questionId',
  1133. for: 'preview',
  1134. relPath: '$relPath'
  1135. });
  1136. </script>
  1137. ";
  1138. return;
  1139. }
  1140. }
  1141. if (!$only_questions) {
  1142. if ($show_title) {
  1143. TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
  1144. echo $objQuestionTmp->getTitleToDisplay($current_item);
  1145. }
  1146. //@todo I need to the get the feedback type
  1147. echo <<<HOTSPOT
  1148. <input type="hidden" name="hidden_hotspot_id" value="$questionId" />
  1149. <div class="exercise_questions">
  1150. $questionDescription
  1151. <div class="row">
  1152. HOTSPOT;
  1153. }
  1154. $relPath = api_get_path(WEB_CODE_PATH);
  1155. $s .= "<div class=\"col-sm-8 col-md-9\">
  1156. <div class=\"hotspot-image\"></div>
  1157. <script>
  1158. $(document).on('ready', function () {
  1159. new ".($answerType == HOT_SPOT_DELINEATION ? 'DelineationQuestion' : 'HotspotQuestion')."({
  1160. questionId: $questionId,
  1161. exerciseId: $exe_id,
  1162. selector: '#question_div_' + $questionId + ' .hotspot-image',
  1163. for: 'user',
  1164. relPath: '$relPath'
  1165. });
  1166. });
  1167. </script>
  1168. </div>
  1169. <div class=\"col-sm-4 col-md-3\">
  1170. $answerList
  1171. </div>
  1172. ";
  1173. echo <<<HOTSPOT
  1174. $s
  1175. </div>
  1176. </div>
  1177. HOTSPOT;
  1178. } elseif ($answerType == ANNOTATION) {
  1179. global $exe_id;
  1180. $relPath = api_get_path(WEB_CODE_PATH);
  1181. if (api_is_platform_admin() || api_is_course_admin()) {
  1182. $docId = DocumentManager::get_document_id($course, '/images/'.$pictureName);
  1183. if ($docId) {
  1184. $images_folder_visibility = api_get_item_visibility(
  1185. $course,
  1186. 'document',
  1187. $docId,
  1188. api_get_session_id()
  1189. );
  1190. if (!$images_folder_visibility) {
  1191. echo Display::return_message(get_lang('ChangeTheVisibilityOfTheCurrentImage'), 'warning');
  1192. }
  1193. }
  1194. if ($freeze) {
  1195. echo Display::img(
  1196. api_get_path(WEB_COURSE_PATH).$course['path'].'/document/images/'.$pictureName,
  1197. $objQuestionTmp->selectTitle(),
  1198. ['width' => '600px']
  1199. );
  1200. return 0;
  1201. }
  1202. }
  1203. if (!$only_questions) {
  1204. if ($show_title) {
  1205. TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
  1206. echo $objQuestionTmp->getTitleToDisplay($current_item);
  1207. }
  1208. echo '
  1209. <input type="hidden" name="hidden_hotspot_id" value="'.$questionId.'" />
  1210. <div class="exercise_questions">
  1211. '.$objQuestionTmp->selectDescription().'
  1212. <div class="row">
  1213. <div class="col-sm-8 col-md-9">
  1214. <div id="annotation-canvas-'.$questionId.'" class="annotation-canvas center-block">
  1215. </div>
  1216. <script>
  1217. AnnotationQuestion({
  1218. questionId: '.$questionId.',
  1219. exerciseId: '.$exe_id.',
  1220. relPath: \''.$relPath.'\'
  1221. });
  1222. </script>
  1223. </div>
  1224. <div class="col-sm-4 col-md-3">
  1225. <div class="well well-sm" id="annotation-toolbar-'.$questionId.'">
  1226. <div class="btn-toolbar">
  1227. <div class="btn-group" data-toggle="buttons">
  1228. <label class="btn btn-default active"
  1229. aria-label="'.get_lang('AddAnnotationPath').'">
  1230. <input type="radio" value="0" name="'.$questionId.'-options" autocomplete="off" checked>
  1231. <span class="fa fa-pencil" aria-hidden="true"></span>
  1232. </label>
  1233. <label class="btn btn-default"
  1234. aria-label="'.get_lang('AddAnnotationText').'">
  1235. <input type="radio" value="1" name="'.$questionId.'-options" autocomplete="off">
  1236. <span class="fa fa-font fa-fw" aria-hidden="true"></span>
  1237. </label>
  1238. </div>
  1239. </div>
  1240. <ul class="list-unstyled"></ul>
  1241. </div>
  1242. </div>
  1243. </div>
  1244. </div>
  1245. ';
  1246. }
  1247. $objAnswerTmp = new Answer($questionId);
  1248. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  1249. unset($objAnswerTmp, $objQuestionTmp);
  1250. }
  1251. return $nbrAnswers;
  1252. }
  1253. /**
  1254. * @param int $exe_id
  1255. * @return array
  1256. */
  1257. public static function get_exercise_track_exercise_info($exe_id)
  1258. {
  1259. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1260. $TBL_TRACK_EXERCICES = Database::get_main_table(
  1261. TABLE_STATISTIC_TRACK_E_EXERCISES
  1262. );
  1263. $TBL_COURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  1264. $exe_id = intval($exe_id);
  1265. $result = array();
  1266. if (!empty($exe_id)) {
  1267. $sql = " SELECT q.*, tee.*
  1268. FROM $TBL_EXERCICES as q
  1269. INNER JOIN $TBL_TRACK_EXERCICES as tee
  1270. ON q.id = tee.exe_exo_id
  1271. INNER JOIN $TBL_COURSE c
  1272. ON c.id = tee.c_id
  1273. WHERE tee.exe_id = $exe_id
  1274. AND q.c_id = c.id";
  1275. $res_fb_type = Database::query($sql);
  1276. $result = Database::fetch_array($res_fb_type, 'ASSOC');
  1277. }
  1278. return $result;
  1279. }
  1280. /**
  1281. * Validates the time control key
  1282. * @param int $exercise_id
  1283. * @param int $lp_id
  1284. * @param int $lp_item_id
  1285. * @return bool
  1286. */
  1287. public static function exercise_time_control_is_valid(
  1288. $exercise_id,
  1289. $lp_id = 0,
  1290. $lp_item_id = 0
  1291. ) {
  1292. $course_id = api_get_course_int_id();
  1293. $exercise_id = intval($exercise_id);
  1294. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  1295. $sql = "SELECT expired_time FROM $table
  1296. WHERE c_id = $course_id AND id = $exercise_id";
  1297. $result = Database::query($sql);
  1298. $row = Database::fetch_array($result, 'ASSOC');
  1299. if (!empty($row['expired_time'])) {
  1300. $current_expired_time_key = self::get_time_control_key(
  1301. $exercise_id,
  1302. $lp_id,
  1303. $lp_item_id
  1304. );
  1305. if (isset($_SESSION['expired_time'][$current_expired_time_key])) {
  1306. $current_time = time();
  1307. $expired_time = api_strtotime(
  1308. $_SESSION['expired_time'][$current_expired_time_key],
  1309. 'UTC'
  1310. );
  1311. $total_time_allowed = $expired_time + 30;
  1312. if ($total_time_allowed < $current_time) {
  1313. return false;
  1314. }
  1315. return true;
  1316. } else {
  1317. return false;
  1318. }
  1319. } else {
  1320. return true;
  1321. }
  1322. }
  1323. /**
  1324. * Deletes the time control token
  1325. *
  1326. * @param int $exercise_id
  1327. * @param int $lp_id
  1328. * @param int $lp_item_id
  1329. */
  1330. public static function exercise_time_control_delete(
  1331. $exercise_id,
  1332. $lp_id = 0,
  1333. $lp_item_id = 0
  1334. ) {
  1335. $current_expired_time_key = self::get_time_control_key(
  1336. $exercise_id,
  1337. $lp_id,
  1338. $lp_item_id
  1339. );
  1340. unset($_SESSION['expired_time'][$current_expired_time_key]);
  1341. }
  1342. /**
  1343. * Generates the time control key
  1344. * @param int $exercise_id
  1345. * @param int $lp_id
  1346. * @param int $lp_item_id
  1347. * @return string
  1348. */
  1349. public static function get_time_control_key(
  1350. $exercise_id,
  1351. $lp_id = 0,
  1352. $lp_item_id = 0
  1353. ) {
  1354. $exercise_id = intval($exercise_id);
  1355. $lp_id = intval($lp_id);
  1356. $lp_item_id = intval($lp_item_id);
  1357. return
  1358. api_get_course_int_id().'_'.
  1359. api_get_session_id().'_'.
  1360. $exercise_id.'_'.
  1361. api_get_user_id().'_'.
  1362. $lp_id.'_'.
  1363. $lp_item_id;
  1364. }
  1365. /**
  1366. * Get session time control
  1367. *
  1368. * @param int $exercise_id
  1369. * @param int $lp_id
  1370. * @param int $lp_item_id
  1371. * @return int
  1372. */
  1373. public static function get_session_time_control_key(
  1374. $exercise_id,
  1375. $lp_id = 0,
  1376. $lp_item_id = 0
  1377. ) {
  1378. $return_value = 0;
  1379. $time_control_key = self::get_time_control_key(
  1380. $exercise_id,
  1381. $lp_id,
  1382. $lp_item_id
  1383. );
  1384. if (isset($_SESSION['expired_time']) && isset($_SESSION['expired_time'][$time_control_key])) {
  1385. $return_value = $_SESSION['expired_time'][$time_control_key];
  1386. }
  1387. return $return_value;
  1388. }
  1389. /**
  1390. * Gets count of exam results
  1391. * @param int $exerciseId
  1392. * @param array $conditions
  1393. * @param string $courseCode
  1394. * @param bool $showSession
  1395. *
  1396. * @return array
  1397. */
  1398. public static function get_count_exam_results($exerciseId, $conditions, $courseCode = '', $showSession = false)
  1399. {
  1400. $count = self::get_exam_results_data(
  1401. null,
  1402. null,
  1403. null,
  1404. null,
  1405. $exerciseId,
  1406. $conditions,
  1407. true,
  1408. $courseCode,
  1409. $showSession
  1410. );
  1411. return $count;
  1412. }
  1413. /**
  1414. * @param string $in_hotpot_path
  1415. * @return int
  1416. */
  1417. public static function get_count_exam_hotpotatoes_results($in_hotpot_path)
  1418. {
  1419. return self::get_exam_results_hotpotatoes_data(
  1420. 0,
  1421. 0,
  1422. '',
  1423. '',
  1424. $in_hotpot_path,
  1425. true,
  1426. ''
  1427. );
  1428. }
  1429. /**
  1430. * @param int $in_from
  1431. * @param int $in_number_of_items
  1432. * @param int $in_column
  1433. * @param int $in_direction
  1434. * @param string $in_hotpot_path
  1435. * @param bool $in_get_count
  1436. * @param null $where_condition
  1437. * @return array|int
  1438. */
  1439. public static function get_exam_results_hotpotatoes_data(
  1440. $in_from,
  1441. $in_number_of_items,
  1442. $in_column,
  1443. $in_direction,
  1444. $in_hotpot_path,
  1445. $in_get_count = false,
  1446. $where_condition = null
  1447. ) {
  1448. $courseId = api_get_course_int_id();
  1449. // by default in_column = 1 If parameters given, it is the name of the column witch is the bdd field name
  1450. if ($in_column == 1) {
  1451. $in_column = 'firstname';
  1452. }
  1453. $in_hotpot_path = Database::escape_string($in_hotpot_path);
  1454. $in_direction = Database::escape_string($in_direction);
  1455. $in_column = Database::escape_string($in_column);
  1456. $in_number_of_items = intval($in_number_of_items);
  1457. $in_from = intval($in_from);
  1458. $TBL_TRACK_HOTPOTATOES = Database::get_main_table(
  1459. TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  1460. );
  1461. $TBL_USER = Database::get_main_table(TABLE_MAIN_USER);
  1462. $sql = "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp
  1463. JOIN $TBL_USER u ON thp.exe_user_id = u.user_id
  1464. WHERE thp.c_id = $courseId AND exe_name LIKE '$in_hotpot_path%'";
  1465. // just count how many answers
  1466. if ($in_get_count) {
  1467. $res = Database::query($sql);
  1468. return Database::num_rows($res);
  1469. }
  1470. // get a number of sorted results
  1471. $sql .= " $where_condition
  1472. ORDER BY $in_column $in_direction
  1473. LIMIT $in_from, $in_number_of_items";
  1474. $res = Database::query($sql);
  1475. $result = array();
  1476. $apiIsAllowedToEdit = api_is_allowed_to_edit();
  1477. $urlBase = api_get_path(WEB_CODE_PATH).
  1478. 'exercise/hotpotatoes_exercise_report.php?action=delete&'.
  1479. api_get_cidreq().'&id=';
  1480. while ($data = Database::fetch_array($res)) {
  1481. $actions = null;
  1482. if ($apiIsAllowedToEdit) {
  1483. $url = $urlBase.$data['id'].'&path='.$data['exe_name'];
  1484. $actions = Display::url(
  1485. Display::return_icon('delete.png', get_lang('Delete')),
  1486. $url
  1487. );
  1488. }
  1489. $result[] = array(
  1490. 'firstname' => $data['firstname'],
  1491. 'lastname' => $data['lastname'],
  1492. 'username' => $data['username'],
  1493. 'group_name' => implode(
  1494. "<br/>",
  1495. GroupManager::get_user_group_name($data['user_id'])
  1496. ),
  1497. 'exe_date' => $data['exe_date'],
  1498. 'score' => $data['exe_result'].' / '.$data['exe_weighting'],
  1499. 'actions' => $actions,
  1500. );
  1501. }
  1502. return $result;
  1503. }
  1504. /**
  1505. * @param string $exercisePath
  1506. * @param int $userId
  1507. * @param int $courseId
  1508. * @param int $sessionId
  1509. *
  1510. * @return array
  1511. */
  1512. public static function getLatestHotPotatoResult(
  1513. $exercisePath,
  1514. $userId,
  1515. $courseId,
  1516. $sessionId
  1517. ) {
  1518. $table = Database::get_main_table(
  1519. TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  1520. );
  1521. $exercisePath = Database::escape_string($exercisePath);
  1522. $userId = intval($userId);
  1523. $sql = "SELECT * FROM $table
  1524. WHERE
  1525. c_id = $courseId AND
  1526. exe_name LIKE '$exercisePath%' AND
  1527. exe_user_id = $userId
  1528. ORDER BY id
  1529. LIMIT 1";
  1530. $result = Database::query($sql);
  1531. $attempt = array();
  1532. if (Database::num_rows($result)) {
  1533. $attempt = Database::fetch_array($result, 'ASSOC');
  1534. }
  1535. return $attempt;
  1536. }
  1537. /**
  1538. * Gets the exam'data results
  1539. * @todo this function should be moved in a library + no global calls
  1540. * @param int $from
  1541. * @param int $number_of_items
  1542. * @param int $column
  1543. * @param string $direction
  1544. * @param int $exercise_id
  1545. * @param null $extra_where_conditions
  1546. * @param bool $get_count
  1547. * @param string $courseCode
  1548. * @return array
  1549. */
  1550. public static function get_exam_results_data(
  1551. $from,
  1552. $number_of_items,
  1553. $column,
  1554. $direction,
  1555. $exercise_id,
  1556. $extra_where_conditions = null,
  1557. $get_count = false,
  1558. $courseCode = null,
  1559. $showSessionField = false,
  1560. $showExerciseCategories = false
  1561. ) {
  1562. //@todo replace all this globals
  1563. global $documentPath, $filter;
  1564. $courseCode = empty($courseCode) ? api_get_course_id() : $courseCode;
  1565. $courseInfo = api_get_course_info($courseCode);
  1566. if (empty($courseInfo)) {
  1567. return [];
  1568. }
  1569. $course_id = $courseInfo['real_id'];
  1570. $is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_allowed_to_edit(true) || api_is_drh() || api_is_student_boss();
  1571. $TBL_USER = Database::get_main_table(TABLE_MAIN_USER);
  1572. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1573. $TBL_GROUP_REL_USER = Database::get_course_table(TABLE_GROUP_USER);
  1574. $TBL_GROUP = Database::get_course_table(TABLE_GROUP);
  1575. $TBL_TRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1576. $TBL_TRACK_HOTPOTATOES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  1577. $TBL_TRACK_ATTEMPT_RECORDING = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  1578. $sessionId = api_get_session_id();
  1579. $session_id_and = '';
  1580. $sessionCondition = '';
  1581. if (!$showSessionField) {
  1582. $session_id_and = " AND te.session_id = $sessionId ";
  1583. $sessionCondition = " AND ttte.session_id = $sessionId";
  1584. }
  1585. $exercise_id = intval($exercise_id);
  1586. $exercise_where = '';
  1587. if (!empty($exercise_id)) {
  1588. $exercise_where .= ' AND te.exe_exo_id = '.$exercise_id.' ';
  1589. }
  1590. $hotpotatoe_where = '';
  1591. if (!empty($_GET['path'])) {
  1592. $hotpotatoe_path = Database::escape_string($_GET['path']);
  1593. $hotpotatoe_where .= ' AND exe_name = "'.$hotpotatoe_path.'" ';
  1594. }
  1595. // sql for chamilo-type tests for teacher / tutor view
  1596. $sql_inner_join_tbl_track_exercices = "
  1597. (
  1598. SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised
  1599. FROM $TBL_TRACK_EXERCICES ttte
  1600. LEFT JOIN $TBL_TRACK_ATTEMPT_RECORDING tr
  1601. ON (ttte.exe_id = tr.exe_id)
  1602. WHERE
  1603. c_id = $course_id AND
  1604. exe_exo_id = $exercise_id
  1605. $sessionCondition
  1606. )";
  1607. if ($is_allowedToEdit) {
  1608. //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries
  1609. // Hack in order to filter groups
  1610. $sql_inner_join_tbl_user = '';
  1611. if (strpos($extra_where_conditions, 'group_id')) {
  1612. $sql_inner_join_tbl_user = "
  1613. (
  1614. SELECT
  1615. u.user_id,
  1616. firstname,
  1617. lastname,
  1618. official_code,
  1619. email,
  1620. username,
  1621. g.name as group_name,
  1622. g.id as group_id
  1623. FROM $TBL_USER u
  1624. INNER JOIN $TBL_GROUP_REL_USER gru
  1625. ON (gru.user_id = u.user_id AND gru.c_id= $course_id )
  1626. INNER JOIN $TBL_GROUP g
  1627. ON (gru.group_id = g.id AND g.c_id= $course_id )
  1628. )";
  1629. }
  1630. if (strpos($extra_where_conditions, 'group_all')) {
  1631. $extra_where_conditions = str_replace(
  1632. "AND ( group_id = 'group_all' )",
  1633. '',
  1634. $extra_where_conditions
  1635. );
  1636. $extra_where_conditions = str_replace(
  1637. "AND group_id = 'group_all'",
  1638. '',
  1639. $extra_where_conditions
  1640. );
  1641. $extra_where_conditions = str_replace(
  1642. "group_id = 'group_all' AND",
  1643. '',
  1644. $extra_where_conditions
  1645. );
  1646. $sql_inner_join_tbl_user = "
  1647. (
  1648. SELECT
  1649. u.user_id,
  1650. firstname,
  1651. lastname,
  1652. official_code,
  1653. email,
  1654. username,
  1655. '' as group_name,
  1656. '' as group_id
  1657. FROM $TBL_USER u
  1658. )";
  1659. $sql_inner_join_tbl_user = null;
  1660. }
  1661. if (strpos($extra_where_conditions, 'group_none')) {
  1662. $extra_where_conditions = str_replace(
  1663. "AND ( group_id = 'group_none' )",
  1664. "AND ( group_id is null )",
  1665. $extra_where_conditions
  1666. );
  1667. $extra_where_conditions = str_replace(
  1668. "AND group_id = 'group_none'",
  1669. "AND ( group_id is null )",
  1670. $extra_where_conditions
  1671. );
  1672. $sql_inner_join_tbl_user = "
  1673. (
  1674. SELECT
  1675. u.user_id,
  1676. firstname,
  1677. lastname,
  1678. official_code,
  1679. email,
  1680. username,
  1681. g.name as group_name,
  1682. g.id as group_id
  1683. FROM $TBL_USER u
  1684. LEFT OUTER JOIN $TBL_GROUP_REL_USER gru
  1685. ON ( gru.user_id = u.user_id AND gru.c_id= $course_id )
  1686. LEFT OUTER JOIN $TBL_GROUP g
  1687. ON (gru.group_id = g.id AND g.c_id = $course_id )
  1688. )";
  1689. }
  1690. // All
  1691. $is_empty_sql_inner_join_tbl_user = false;
  1692. if (empty($sql_inner_join_tbl_user)) {
  1693. $is_empty_sql_inner_join_tbl_user = true;
  1694. $sql_inner_join_tbl_user = "
  1695. (
  1696. SELECT u.user_id, firstname, lastname, email, username, ' ' as group_name, '' as group_id, official_code
  1697. FROM $TBL_USER u
  1698. WHERE u.status NOT IN(".api_get_users_status_ignored_in_reports('string').")
  1699. )";
  1700. }
  1701. $sqlFromOption = " , $TBL_GROUP_REL_USER AS gru ";
  1702. $sqlWhereOption = " AND gru.c_id = $course_id AND gru.user_id = user.user_id ";
  1703. $first_and_last_name = api_is_western_name_order() ? "firstname, lastname" : "lastname, firstname";
  1704. if ($get_count) {
  1705. $sql_select = "SELECT count(te.exe_id) ";
  1706. } else {
  1707. $sql_select = "SELECT DISTINCT
  1708. user_id,
  1709. $first_and_last_name,
  1710. official_code,
  1711. ce.title,
  1712. username,
  1713. te.exe_result,
  1714. te.exe_weighting,
  1715. te.exe_date,
  1716. te.exe_id,
  1717. te.session_id,
  1718. email as exemail,
  1719. te.start_date,
  1720. ce.expired_time,
  1721. steps_counter,
  1722. exe_user_id,
  1723. te.exe_duration,
  1724. te.status as completion_status,
  1725. propagate_neg,
  1726. revised,
  1727. group_name,
  1728. group_id,
  1729. orig_lp_id,
  1730. te.user_ip";
  1731. }
  1732. $sql = " $sql_select
  1733. FROM $TBL_EXERCICES AS ce
  1734. INNER JOIN $sql_inner_join_tbl_track_exercices AS te
  1735. ON (te.exe_exo_id = ce.id)
  1736. INNER JOIN $sql_inner_join_tbl_user AS user
  1737. ON (user.user_id = exe_user_id)
  1738. WHERE
  1739. te.c_id = $course_id $session_id_and AND
  1740. ce.active <> -1 AND
  1741. ce.c_id = $course_id
  1742. $exercise_where
  1743. $extra_where_conditions
  1744. ";
  1745. // sql for hotpotatoes tests for teacher / tutor view
  1746. if ($get_count) {
  1747. $hpsql_select = "SELECT count(username)";
  1748. } else {
  1749. $hpsql_select = "SELECT
  1750. $first_and_last_name ,
  1751. username,
  1752. official_code,
  1753. tth.exe_name,
  1754. tth.exe_result ,
  1755. tth.exe_weighting,
  1756. tth.exe_date";
  1757. }
  1758. $hpsql = " $hpsql_select
  1759. FROM
  1760. $TBL_TRACK_HOTPOTATOES tth,
  1761. $TBL_USER user
  1762. $sqlFromOption
  1763. WHERE
  1764. user.user_id=tth.exe_user_id
  1765. AND tth.c_id = $course_id
  1766. $hotpotatoe_where
  1767. $sqlWhereOption
  1768. AND user.status NOT IN(".api_get_users_status_ignored_in_reports('string').")
  1769. ORDER BY
  1770. tth.c_id ASC,
  1771. tth.exe_date DESC";
  1772. }
  1773. if (empty($sql)) {
  1774. return false;
  1775. }
  1776. if ($get_count) {
  1777. $resx = Database::query($sql);
  1778. $rowx = Database::fetch_row($resx, 'ASSOC');
  1779. return $rowx[0];
  1780. }
  1781. $teacher_list = CourseManager::get_teacher_list_from_course_code(
  1782. $courseCode
  1783. );
  1784. $teacher_id_list = array();
  1785. if (!empty($teacher_list)) {
  1786. foreach ($teacher_list as $teacher) {
  1787. $teacher_id_list[] = $teacher['user_id'];
  1788. }
  1789. }
  1790. $list_info = array();
  1791. // Simple exercises
  1792. if (empty($hotpotatoe_where)) {
  1793. $column = !empty($column) ? Database::escape_string($column) : null;
  1794. $from = intval($from);
  1795. $number_of_items = intval($number_of_items);
  1796. if (!empty($column)) {
  1797. $sql .= " ORDER BY $column $direction ";
  1798. }
  1799. $sql .= " LIMIT $from, $number_of_items";
  1800. $results = array();
  1801. $resx = Database::query($sql);
  1802. while ($rowx = Database::fetch_array($resx, 'ASSOC')) {
  1803. $results[] = $rowx;
  1804. }
  1805. $group_list = GroupManager::get_group_list(null, $courseInfo);
  1806. $clean_group_list = array();
  1807. if (!empty($group_list)) {
  1808. foreach ($group_list as $group) {
  1809. $clean_group_list[$group['id']] = $group['name'];
  1810. }
  1811. }
  1812. $lp_list_obj = new LearnpathList(api_get_user_id());
  1813. $lp_list = $lp_list_obj->get_flat_list();
  1814. $oldIds = array_column($lp_list, 'lp_old_id', 'iid');
  1815. if (is_array($results)) {
  1816. $users_array_id = array();
  1817. $from_gradebook = false;
  1818. if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
  1819. $from_gradebook = true;
  1820. }
  1821. $sizeof = count($results);
  1822. $user_list_id = array();
  1823. $locked = api_resource_is_locked_by_gradebook(
  1824. $exercise_id,
  1825. LINK_EXERCISE
  1826. );
  1827. $timeNow = strtotime(api_get_utc_datetime());
  1828. // Looping results
  1829. for ($i = 0; $i < $sizeof; $i++) {
  1830. $revised = $results[$i]['revised'];
  1831. if ($results[$i]['completion_status'] == 'incomplete') {
  1832. // If the exercise was incomplete, we need to determine
  1833. // if it is still into the time allowed, or if its
  1834. // allowed time has expired and it can be closed
  1835. // (it's "unclosed")
  1836. $minutes = $results[$i]['expired_time'];
  1837. if ($minutes == 0) {
  1838. // There's no time limit, so obviously the attempt
  1839. // can still be "ongoing", but the teacher should
  1840. // be able to choose to close it, so mark it as
  1841. // "unclosed" instead of "ongoing"
  1842. $revised = 2;
  1843. } else {
  1844. $allowedSeconds = $minutes * 60;
  1845. $timeAttemptStarted = strtotime($results[$i]['start_date']);
  1846. $secondsSinceStart = $timeNow - $timeAttemptStarted;
  1847. if ($secondsSinceStart > $allowedSeconds) {
  1848. $revised = 2; // mark as "unclosed"
  1849. } else {
  1850. $revised = 3; // mark as "ongoing"
  1851. }
  1852. }
  1853. }
  1854. if ($from_gradebook && ($is_allowedToEdit)) {
  1855. if (in_array(
  1856. $results[$i]['username'].$results[$i]['firstname'].$results[$i]['lastname'],
  1857. $users_array_id
  1858. )) {
  1859. continue;
  1860. }
  1861. $users_array_id[] = $results[$i]['username'].$results[$i]['firstname'].$results[$i]['lastname'];
  1862. }
  1863. $lp_obj = isset($results[$i]['orig_lp_id']) && isset($lp_list[$results[$i]['orig_lp_id']]) ? $lp_list[$results[$i]['orig_lp_id']] : null;
  1864. if (empty($lp_obj)) {
  1865. // Try to get the old id (id instead of iid)
  1866. $lpNewId = isset($results[$i]['orig_lp_id']) && isset($oldIds[$results[$i]['orig_lp_id']]) ? $oldIds[$results[$i]['orig_lp_id']] : null;
  1867. if ($lpNewId) {
  1868. $lp_obj = isset($lp_list[$lpNewId]) ? $lp_list[$lpNewId] : null;
  1869. }
  1870. }
  1871. $lp_name = null;
  1872. if ($lp_obj) {
  1873. $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$results[$i]['orig_lp_id'];
  1874. $lp_name = Display::url(
  1875. $lp_obj['lp_name'],
  1876. $url,
  1877. array('target' => '_blank')
  1878. );
  1879. }
  1880. // Add all groups by user
  1881. $group_name_list = null;
  1882. if ($is_empty_sql_inner_join_tbl_user) {
  1883. $group_list = GroupManager::get_group_ids(
  1884. api_get_course_int_id(),
  1885. $results[$i]['user_id']
  1886. );
  1887. foreach ($group_list as $id) {
  1888. $group_name_list .= $clean_group_list[$id].'<br/>';
  1889. }
  1890. $results[$i]['group_name'] = $group_name_list;
  1891. }
  1892. $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round($results[$i]['exe_duration'] / 60) : 0;
  1893. $user_list_id[] = $results[$i]['exe_user_id'];
  1894. $id = $results[$i]['exe_id'];
  1895. $dt = api_convert_and_format_date($results[$i]['exe_weighting']);
  1896. // we filter the results if we have the permission to
  1897. if (isset($results[$i]['results_disabled'])) {
  1898. $result_disabled = intval(
  1899. $results[$i]['results_disabled']
  1900. );
  1901. } else {
  1902. $result_disabled = 0;
  1903. }
  1904. if ($result_disabled == 0) {
  1905. $my_res = $results[$i]['exe_result'];
  1906. $my_total = $results[$i]['exe_weighting'];
  1907. $results[$i]['start_date'] = api_get_local_time(
  1908. $results[$i]['start_date']
  1909. );
  1910. $results[$i]['exe_date'] = api_get_local_time(
  1911. $results[$i]['exe_date']
  1912. );
  1913. if (!$results[$i]['propagate_neg'] && $my_res < 0) {
  1914. $my_res = 0;
  1915. }
  1916. $score = self::show_score($my_res, $my_total);
  1917. $actions = '<div class="pull-right">';
  1918. if ($is_allowedToEdit) {
  1919. if (isset($teacher_id_list)) {
  1920. if (in_array(
  1921. $results[$i]['exe_user_id'],
  1922. $teacher_id_list
  1923. )) {
  1924. $actions .= Display::return_icon(
  1925. 'teacher.png',
  1926. get_lang('Teacher')
  1927. );
  1928. }
  1929. }
  1930. $revisedLabel = '';
  1931. switch ($revised) {
  1932. case 0:
  1933. $actions .= "<a href='exercise_show.php?".api_get_cidreq()."&action=qualify&id=$id'>".
  1934. Display:: return_icon(
  1935. 'quiz.png',
  1936. get_lang('Qualify')
  1937. );
  1938. $actions .= '</a>';
  1939. $revisedLabel = Display::label(
  1940. get_lang('NotValidated'),
  1941. 'info'
  1942. );
  1943. break;
  1944. case 1:
  1945. $actions .= "<a href='exercise_show.php?".api_get_cidreq()."&action=edit&id=$id'>".
  1946. Display:: return_icon(
  1947. 'edit.png',
  1948. get_lang('Edit'),
  1949. array(),
  1950. ICON_SIZE_SMALL
  1951. );
  1952. $actions .= '</a>';
  1953. $revisedLabel = Display::label(
  1954. get_lang('Validated'),
  1955. 'success'
  1956. );
  1957. break;
  1958. case 2: //finished but not marked as such
  1959. $actions .= '<a href="exercise_report.php?'
  1960. .api_get_cidreq()
  1961. .'&exerciseId='
  1962. .$exercise_id
  1963. .'&a=close&id='
  1964. .$id
  1965. .'">'.
  1966. Display:: return_icon(
  1967. 'lock.png',
  1968. get_lang('MarkAttemptAsClosed'),
  1969. array(),
  1970. ICON_SIZE_SMALL
  1971. );
  1972. $actions .= '</a>';
  1973. $revisedLabel = Display::label(
  1974. get_lang('Unclosed'),
  1975. 'warning'
  1976. );
  1977. break;
  1978. case 3: //still ongoing
  1979. $actions .= Display:: return_icon(
  1980. 'clock.png',
  1981. get_lang('AttemptStillOngoingPleaseWait'),
  1982. array(),
  1983. ICON_SIZE_SMALL
  1984. );
  1985. $actions .= '';
  1986. $revisedLabel = Display::label(
  1987. get_lang('Ongoing'),
  1988. 'danger'
  1989. );
  1990. break;
  1991. }
  1992. if ($filter == 2) {
  1993. $actions .= ' <a href="exercise_history.php?'.api_get_cidreq().'&exe_id='.$id.'">'.
  1994. Display:: return_icon(
  1995. 'history.png',
  1996. get_lang('ViewHistoryChange')
  1997. ).'</a>';
  1998. }
  1999. // Admin can always delete the attempt
  2000. if (($locked == false || api_is_platform_admin()) && !api_is_student_boss()) {
  2001. $ip = Tracking::get_ip_from_user_event(
  2002. $results[$i]['exe_user_id'],
  2003. api_get_utc_datetime(),
  2004. false
  2005. );
  2006. $actions .= '<a href="http://www.whatsmyip.org/ip-geo-location/?ip='.$ip.'" target="_blank">'
  2007. .Display::return_icon('info.png', $ip)
  2008. .'</a>';
  2009. $recalculateUrl = api_get_path(WEB_CODE_PATH).'exercise/recalculate.php?'.
  2010. api_get_cidreq().'&'.
  2011. http_build_query([
  2012. 'id' => $id,
  2013. 'exercise' => $exercise_id,
  2014. 'user' => $results[$i]['exe_user_id']
  2015. ]);
  2016. $actions .= Display::url(
  2017. Display::return_icon('reload.png', get_lang('RecalculateResults')),
  2018. $recalculateUrl,
  2019. [
  2020. 'data-exercise' => $exercise_id,
  2021. 'data-user' => $results[$i]['exe_user_id'],
  2022. 'data-id' => $id,
  2023. 'class' => 'exercise-recalculate'
  2024. ]
  2025. );
  2026. $filterByUser = isset($_GET['filter_by_user']) ? (int) $_GET['filter_by_user'] : 0;
  2027. $delete_link = '<a href="exercise_report.php?'.api_get_cidreq().'&filter_by_user='.$filterByUser.'&filter='.$filter.'&exerciseId='.$exercise_id.'&delete=delete&did='.$id.'"
  2028. onclick="javascript:if(!confirm(\'' . sprintf(
  2029. get_lang('DeleteAttempt'),
  2030. $results[$i]['username'],
  2031. $dt
  2032. ).'\')) return false;">';
  2033. $delete_link .=
  2034. Display:: return_icon(
  2035. 'delete.png',
  2036. get_lang('Delete')
  2037. ).'</a>';
  2038. $delete_link = utf8_encode($delete_link);
  2039. if (api_is_drh() && !api_is_platform_admin()) {
  2040. $delete_link = null;
  2041. }
  2042. if ($revised == 3) {
  2043. $delete_link = null;
  2044. }
  2045. $actions .= $delete_link;
  2046. }
  2047. } else {
  2048. $attempt_url = api_get_path(WEB_CODE_PATH).'exercise/result.php?'.api_get_cidreq().'&id='.$results[$i]['exe_id'].'&id_session='.$sessionId;
  2049. $attempt_link = Display::url(
  2050. get_lang('Show'),
  2051. $attempt_url,
  2052. [
  2053. 'class' => 'ajax btn btn-default',
  2054. 'data-title' => get_lang('Show')
  2055. ]
  2056. );
  2057. $actions .= $attempt_link;
  2058. }
  2059. $actions .= '</div>';
  2060. $exeId = $results[$i]['exe_id'];
  2061. $results[$i]['id'] = $exeId;
  2062. $category_list = [];
  2063. if ($is_allowedToEdit) {
  2064. $sessionName = '';
  2065. if (!empty($results[$i]['session_id'])) {
  2066. $sessionName = api_get_session_name($results[$i]['session_id']);
  2067. }
  2068. $objExercise = new Exercise($course_id);
  2069. if ($showExerciseCategories) {
  2070. $question_list = array();
  2071. // Getting attempt info
  2072. $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exeId);
  2073. if (!empty($exercise_stat_info['data_tracking'])) {
  2074. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  2075. if (!empty($question_list)) {
  2076. foreach ($question_list as $questionId) {
  2077. $objQuestionTmp = Question::read($questionId, $course_id);
  2078. // We're inside *one* question. Go through each possible answer for this question
  2079. $result = $objExercise->manage_answer(
  2080. $exeId,
  2081. $questionId,
  2082. null,
  2083. 'exercise_result',
  2084. false,
  2085. false,
  2086. true,
  2087. false,
  2088. $objExercise->selectPropagateNeg(),
  2089. null,
  2090. true
  2091. );
  2092. $my_total_score = $result['score'];
  2093. $my_total_weight = $result['weight'];
  2094. // Category report
  2095. $category_was_added_for_this_test = false;
  2096. if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) {
  2097. if (!isset($category_list[$objQuestionTmp->category]['score'])) {
  2098. $category_list[$objQuestionTmp->category]['score'] = 0;
  2099. }
  2100. if (!isset($category_list[$objQuestionTmp->category]['total'])) {
  2101. $category_list[$objQuestionTmp->category]['total'] = 0;
  2102. }
  2103. $category_list[$objQuestionTmp->category]['score'] += $my_total_score;
  2104. $category_list[$objQuestionTmp->category]['total'] += $my_total_weight;
  2105. $category_was_added_for_this_test = true;
  2106. }
  2107. if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) {
  2108. foreach ($objQuestionTmp->category_list as $category_id) {
  2109. $category_list[$category_id]['score'] += $my_total_score;
  2110. $category_list[$category_id]['total'] += $my_total_weight;
  2111. $category_was_added_for_this_test = true;
  2112. }
  2113. }
  2114. // No category for this question!
  2115. if ($category_was_added_for_this_test == false) {
  2116. if (!isset($category_list['none']['score'])) {
  2117. $category_list['none']['score'] = 0;
  2118. }
  2119. if (!isset($category_list['none']['total'])) {
  2120. $category_list['none']['total'] = 0;
  2121. }
  2122. $category_list['none']['score'] += $my_total_score;
  2123. $category_list['none']['total'] += $my_total_weight;
  2124. }
  2125. }
  2126. }
  2127. }
  2128. }
  2129. foreach ($category_list as $categoryId => $result) {
  2130. $results[$i]['category_'.$categoryId] = self::show_score($result['score'], $result['total']);
  2131. }
  2132. $results[$i]['session'] = $sessionName;
  2133. $results[$i]['status'] = $revisedLabel;
  2134. $results[$i]['score'] = $score;
  2135. $results[$i]['lp'] = $lp_name;
  2136. $results[$i]['actions'] = $actions;
  2137. $list_info[] = $results[$i];
  2138. } else {
  2139. $results[$i]['status'] = $revisedLabel;
  2140. $results[$i]['score'] = $score;
  2141. $results[$i]['actions'] = $actions;
  2142. $list_info[] = $results[$i];
  2143. }
  2144. }
  2145. }
  2146. }
  2147. } else {
  2148. $hpresults = [];
  2149. $res = Database::query($hpsql);
  2150. if ($res !== false) {
  2151. $i = 0;
  2152. while ($resA = Database::fetch_array($res, 'NUM')) {
  2153. for ($j = 0; $j < 6; $j++) {
  2154. $hpresults[$i][$j] = $resA[$j];
  2155. }
  2156. $i++;
  2157. }
  2158. }
  2159. // Print HotPotatoes test results.
  2160. if (is_array($hpresults)) {
  2161. for ($i = 0; $i < sizeof($hpresults); $i++) {
  2162. $hp_title = GetQuizName($hpresults[$i][3], $documentPath);
  2163. if ($hp_title == '') {
  2164. $hp_title = basename($hpresults[$i][3]);
  2165. }
  2166. $hp_date = api_get_local_time(
  2167. $hpresults[$i][6],
  2168. null,
  2169. date_default_timezone_get()
  2170. );
  2171. $hp_result = round(($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1)) * 100, 2)
  2172. .'% ('.$hpresults[$i][4].' / '.$hpresults[$i][5].')';
  2173. if ($is_allowedToEdit) {
  2174. $list_info[] = array(
  2175. $hpresults[$i][0],
  2176. $hpresults[$i][1],
  2177. $hpresults[$i][2],
  2178. '',
  2179. $hp_title,
  2180. '-',
  2181. $hp_date,
  2182. $hp_result,
  2183. '-'
  2184. );
  2185. } else {
  2186. $list_info[] = array(
  2187. $hp_title,
  2188. '-',
  2189. $hp_date,
  2190. $hp_result,
  2191. '-'
  2192. );
  2193. }
  2194. }
  2195. }
  2196. }
  2197. return $list_info;
  2198. }
  2199. /**
  2200. * Converts the score with the exercise_max_note and exercise_min_score
  2201. * the platform settings + formats the results using the float_format function
  2202. *
  2203. * @param float $score
  2204. * @param float $weight
  2205. * @param bool $show_percentage show percentage or not
  2206. * @param bool $use_platform_settings use or not the platform settings
  2207. * @param bool $show_only_percentage
  2208. * @return string an html with the score modified
  2209. */
  2210. public static function show_score(
  2211. $score,
  2212. $weight,
  2213. $show_percentage = true,
  2214. $use_platform_settings = true,
  2215. $show_only_percentage = false
  2216. ) {
  2217. if (is_null($score) && is_null($weight)) {
  2218. return '-';
  2219. }
  2220. $maxNote = api_get_setting('exercise_max_score');
  2221. $minNote = api_get_setting('exercise_min_score');
  2222. if ($use_platform_settings) {
  2223. if ($maxNote != '' && $minNote != '') {
  2224. if (!empty($weight) && intval($weight) != 0) {
  2225. $score = $minNote + ($maxNote - $minNote) * $score / $weight;
  2226. } else {
  2227. $score = $minNote;
  2228. }
  2229. $weight = $maxNote;
  2230. }
  2231. }
  2232. $percentage = (100 * $score) / ($weight != 0 ? $weight : 1);
  2233. // Formats values
  2234. $percentage = float_format($percentage, 1);
  2235. $score = float_format($score, 1);
  2236. $weight = float_format($weight, 1);
  2237. $html = '';
  2238. if ($show_percentage) {
  2239. $parent = '('.$score.' / '.$weight.')';
  2240. $html = $percentage."% $parent";
  2241. if ($show_only_percentage) {
  2242. $html = $percentage."% ";
  2243. }
  2244. } else {
  2245. $html = $score.' / '.$weight;
  2246. }
  2247. // Over write score
  2248. $scoreBasedInModel = self::convertScoreToModel($percentage);
  2249. if (!empty($scoreBasedInModel)) {
  2250. $html = $scoreBasedInModel;
  2251. }
  2252. $html = Display::span($html, ['class' => 'score_exercise']);
  2253. return $html;
  2254. }
  2255. /**
  2256. * @param array $model
  2257. * @param float $percentage
  2258. * @return string
  2259. */
  2260. public static function getModelStyle($model, $percentage)
  2261. {
  2262. //$modelWithStyle = get_lang($model['name']);
  2263. $modelWithStyle = '<span class="'.$model['css_class'].'"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>';
  2264. //$modelWithStyle .= $percentage;
  2265. return $modelWithStyle;
  2266. }
  2267. /**
  2268. * @param float $percentage value between 0 and 100
  2269. * @return string
  2270. */
  2271. public static function convertScoreToModel($percentage)
  2272. {
  2273. $model = self::getCourseScoreModel();
  2274. if (!empty($model)) {
  2275. $scoreWithGrade = [];
  2276. foreach ($model['score_list'] as $item) {
  2277. if ($percentage >= $item['min'] && $percentage <= $item['max']) {
  2278. $scoreWithGrade = $item;
  2279. break;
  2280. }
  2281. }
  2282. if (!empty($scoreWithGrade)) {
  2283. return self::getModelStyle($scoreWithGrade, $percentage);
  2284. }
  2285. }
  2286. return '';
  2287. }
  2288. /**
  2289. * @return array
  2290. */
  2291. public static function getCourseScoreModel()
  2292. {
  2293. $modelList = self::getScoreModels();
  2294. if (empty($modelList)) {
  2295. return [];
  2296. }
  2297. $courseInfo = api_get_course_info();
  2298. if (!empty($courseInfo)) {
  2299. $scoreModelId = api_get_course_setting('score_model_id');
  2300. if ($scoreModelId != -1) {
  2301. $modelIdList = array_column($modelList['models'], 'id');
  2302. if (in_array($scoreModelId, $modelIdList)) {
  2303. foreach ($modelList['models'] as $item) {
  2304. if ($item['id'] == $scoreModelId) {
  2305. return $item;
  2306. }
  2307. }
  2308. }
  2309. }
  2310. }
  2311. return [];
  2312. }
  2313. /**
  2314. * @return array
  2315. */
  2316. public static function getScoreModels()
  2317. {
  2318. return api_get_configuration_value('score_grade_model');
  2319. }
  2320. /**
  2321. * @param float $score
  2322. * @param float $weight
  2323. * @param string $pass_percentage
  2324. * @return bool
  2325. */
  2326. public static function isSuccessExerciseResult($score, $weight, $pass_percentage)
  2327. {
  2328. $percentage = float_format(
  2329. ($score / ($weight != 0 ? $weight : 1)) * 100,
  2330. 1
  2331. );
  2332. if (isset($pass_percentage) && !empty($pass_percentage)) {
  2333. if ($percentage >= $pass_percentage) {
  2334. return true;
  2335. }
  2336. }
  2337. return false;
  2338. }
  2339. /**
  2340. * @param FormValidator $form
  2341. * @param string $name
  2342. * @param $weight
  2343. * @param $selected
  2344. * @return bool
  2345. */
  2346. public static function addScoreModelInput(
  2347. FormValidator & $form,
  2348. $name,
  2349. $weight,
  2350. $selected
  2351. ) {
  2352. $model = self::getCourseScoreModel();
  2353. if (empty($model)) {
  2354. return false;
  2355. }
  2356. /** @var HTML_QuickForm_select $element */
  2357. $element = $form->createElement(
  2358. 'select',
  2359. $name,
  2360. get_lang('Qualification'),
  2361. [],
  2362. ['class' => 'exercise_mark_select']
  2363. );
  2364. foreach ($model['score_list'] as $item) {
  2365. $i = api_number_format($item['score_to_qualify'] / 100 * $weight, 2);
  2366. $label = ExerciseLib::getModelStyle($item, $i);
  2367. $attributes = [
  2368. 'class' => $item['css_class']
  2369. ];
  2370. if ($selected == $i) {
  2371. $attributes['selected'] = 'selected';
  2372. }
  2373. $element->addOption($label, $i, $attributes);
  2374. }
  2375. $form->addElement($element);
  2376. }
  2377. /**
  2378. * @return string
  2379. */
  2380. public static function getJsCode()
  2381. {
  2382. // Filling the scores with the right colors.
  2383. $models = ExerciseLib::getCourseScoreModel();
  2384. $cssListToString = '';
  2385. if (!empty($models)) {
  2386. $cssList = array_column($models['score_list'], 'css_class');
  2387. $cssListToString = implode(' ', $cssList);
  2388. }
  2389. if (empty($cssListToString)) {
  2390. return '';
  2391. }
  2392. $js = <<<EOT
  2393. function updateSelect(element) {
  2394. var spanTag = element.parent().find('span.filter-option');
  2395. var value = element.val();
  2396. var selectId = element.attr('id');
  2397. var optionClass = $('#' + selectId + ' option[value="'+value+'"]').attr('class');
  2398. spanTag.removeClass('$cssListToString');
  2399. spanTag.addClass(optionClass);
  2400. }
  2401. $(document).ready( function() {
  2402. // Loading values
  2403. $('.exercise_mark_select').on('loaded.bs.select', function() {
  2404. updateSelect($(this));
  2405. });
  2406. // On change
  2407. $('.exercise_mark_select').on('changed.bs.select', function() {
  2408. updateSelect($(this));
  2409. });
  2410. });
  2411. EOT;
  2412. return $js;
  2413. }
  2414. /**
  2415. * @param float $score
  2416. * @param float $weight
  2417. * @param string $pass_percentage
  2418. * @return string
  2419. */
  2420. public static function showSuccessMessage($score, $weight, $pass_percentage)
  2421. {
  2422. $res = '';
  2423. if (self::isPassPercentageEnabled($pass_percentage)) {
  2424. $isSuccess = self::isSuccessExerciseResult(
  2425. $score,
  2426. $weight,
  2427. $pass_percentage
  2428. );
  2429. if ($isSuccess) {
  2430. $html = get_lang('CongratulationsYouPassedTheTest');
  2431. $icon = Display::return_icon(
  2432. 'completed.png',
  2433. get_lang('Correct'),
  2434. array(),
  2435. ICON_SIZE_MEDIUM
  2436. );
  2437. } else {
  2438. //$html .= Display::return_message(get_lang('YouDidNotReachTheMinimumScore'), 'warning');
  2439. $html = get_lang('YouDidNotReachTheMinimumScore');
  2440. $icon = Display::return_icon(
  2441. 'warning.png',
  2442. get_lang('Wrong'),
  2443. array(),
  2444. ICON_SIZE_MEDIUM
  2445. );
  2446. }
  2447. $html = Display::tag('h4', $html);
  2448. $html .= Display::tag(
  2449. 'h5',
  2450. $icon,
  2451. array('style' => 'width:40px; padding:2px 10px 0px 0px')
  2452. );
  2453. $res = $html;
  2454. }
  2455. return $res;
  2456. }
  2457. /**
  2458. * Return true if pass_pourcentage activated (we use the pass pourcentage feature
  2459. * return false if pass_percentage = 0 (we don't use the pass pourcentage feature
  2460. * @param $value
  2461. * @return boolean
  2462. * In this version, pass_percentage and show_success_message are disabled if
  2463. * pass_percentage is set to 0
  2464. */
  2465. public static function isPassPercentageEnabled($value)
  2466. {
  2467. return $value > 0;
  2468. }
  2469. /**
  2470. * Converts a numeric value in a percentage example 0.66666 to 66.67 %
  2471. * @param $value
  2472. * @return float Converted number
  2473. */
  2474. public static function convert_to_percentage($value)
  2475. {
  2476. $return = '-';
  2477. if ($value != '') {
  2478. $return = float_format($value * 100, 1).' %';
  2479. }
  2480. return $return;
  2481. }
  2482. /**
  2483. * Converts a score/weight values to the platform scale
  2484. * @param float $score
  2485. * @param float $weight
  2486. * @deprecated seem not to be used
  2487. * @return float the score rounded converted to the new range
  2488. */
  2489. public static function convert_score($score, $weight)
  2490. {
  2491. $maxNote = api_get_setting('exercise_max_score');
  2492. $minNote = api_get_setting('exercise_min_score');
  2493. if ($score != '' && $weight != '') {
  2494. if ($maxNote != '' && $minNote != '') {
  2495. if (!empty($weight)) {
  2496. $score = $minNote + ($maxNote - $minNote) * $score / $weight;
  2497. } else {
  2498. $score = $minNote;
  2499. }
  2500. }
  2501. }
  2502. $score_rounded = float_format($score, 1);
  2503. return $score_rounded;
  2504. }
  2505. /**
  2506. * Getting all active exercises from a course from a session
  2507. * (if a session_id is provided we will show all the exercises in the course +
  2508. * all exercises in the session)
  2509. * @param array $course_info
  2510. * @param int $session_id
  2511. * @param boolean $check_publication_dates
  2512. * @param string $search Search exercise name
  2513. * @param boolean $search_all_sessions Search exercises in all sessions
  2514. * @param int 0 = only inactive exercises
  2515. * 1 = only active exercises,
  2516. * 2 = all exercises
  2517. * 3 = active <> -1
  2518. * @return array array with exercise data
  2519. */
  2520. public static function get_all_exercises(
  2521. $course_info = null,
  2522. $session_id = 0,
  2523. $check_publication_dates = false,
  2524. $search = '',
  2525. $search_all_sessions = false,
  2526. $active = 2
  2527. ) {
  2528. $course_id = api_get_course_int_id();
  2529. if (!empty($course_info) && !empty($course_info['real_id'])) {
  2530. $course_id = $course_info['real_id'];
  2531. }
  2532. if ($session_id == -1) {
  2533. $session_id = 0;
  2534. }
  2535. $now = api_get_utc_datetime();
  2536. $time_conditions = '';
  2537. if ($check_publication_dates) {
  2538. //start and end are set
  2539. $time_conditions = " AND ((start_time <> '' AND start_time < '$now' AND end_time <> '' AND end_time > '$now' ) OR ";
  2540. // only start is set
  2541. $time_conditions .= " (start_time <> '' AND start_time < '$now' AND end_time is NULL) OR ";
  2542. // only end is set
  2543. $time_conditions .= " (start_time IS NULL AND end_time <> '' AND end_time > '$now') OR ";
  2544. // nothing is set
  2545. $time_conditions .= " (start_time IS NULL AND end_time IS NULL)) ";
  2546. }
  2547. $needle_where = !empty($search) ? " AND title LIKE '?' " : '';
  2548. $needle = !empty($search) ? "%".$search."%" : '';
  2549. // Show courses by active status
  2550. $active_sql = '';
  2551. if ($active == 3) {
  2552. $active_sql = ' active <> -1 AND';
  2553. } else {
  2554. if ($active != 2) {
  2555. $active_sql = sprintf(' active = %d AND', $active);
  2556. }
  2557. }
  2558. if ($search_all_sessions == true) {
  2559. $conditions = array(
  2560. 'where' => array(
  2561. $active_sql.' c_id = ? '.$needle_where.$time_conditions => array(
  2562. $course_id,
  2563. $needle
  2564. )
  2565. ),
  2566. 'order' => 'title'
  2567. );
  2568. } else {
  2569. if (empty($session_id)) {
  2570. $conditions = array(
  2571. 'where' => array(
  2572. $active_sql.' (session_id = 0 OR session_id IS NULL) AND c_id = ? '.$needle_where.$time_conditions => array(
  2573. $course_id,
  2574. $needle
  2575. )
  2576. ),
  2577. 'order' => 'title'
  2578. );
  2579. } else {
  2580. $conditions = array(
  2581. 'where' => array(
  2582. $active_sql.' (session_id = 0 OR session_id = ? ) AND c_id = ? '.$needle_where.$time_conditions => array(
  2583. $session_id,
  2584. $course_id,
  2585. $needle
  2586. )
  2587. ),
  2588. 'order' => 'title'
  2589. );
  2590. }
  2591. }
  2592. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  2593. return Database::select('*', $table, $conditions);
  2594. }
  2595. /**
  2596. * Get exercise information by id
  2597. * @param int $exerciseId Exercise Id
  2598. * @param int $courseId The course ID (necessary as c_quiz.id is not unique)
  2599. * @return array Exercise info
  2600. */
  2601. public static function get_exercise_by_id($exerciseId = 0, $courseId = 0)
  2602. {
  2603. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  2604. if (empty($courseId)) {
  2605. $courseId = api_get_course_int_id();
  2606. } else {
  2607. $courseId = intval($courseId);
  2608. }
  2609. $conditions = array(
  2610. 'where' => array(
  2611. 'id = ?' => array($exerciseId),
  2612. ' AND c_id = ? ' => $courseId
  2613. )
  2614. );
  2615. return Database::select('*', $table, $conditions);
  2616. }
  2617. /**
  2618. * Getting all exercises (active only or all)
  2619. * from a course from a session
  2620. * (if a session_id is provided we will show all the exercises in the
  2621. * course + all exercises in the session)
  2622. * @param array course data
  2623. * @param int session id
  2624. * @param int course c_id
  2625. * @param boolean $only_active_exercises
  2626. * @return array array with exercise data
  2627. * modified by Hubert Borderiou
  2628. */
  2629. public static function get_all_exercises_for_course_id(
  2630. $course_info = null,
  2631. $session_id = 0,
  2632. $course_id = 0,
  2633. $only_active_exercises = true
  2634. ) {
  2635. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  2636. if ($only_active_exercises) {
  2637. // Only active exercises.
  2638. $sql_active_exercises = "active = 1 AND ";
  2639. } else {
  2640. // Not only active means visible and invisible NOT deleted (-2)
  2641. $sql_active_exercises = "active IN (1, 0) AND ";
  2642. }
  2643. if ($session_id == -1) {
  2644. $session_id = 0;
  2645. }
  2646. $params = array(
  2647. $session_id,
  2648. $course_id
  2649. );
  2650. if ($session_id == 0) {
  2651. $conditions = array(
  2652. 'where' => array("$sql_active_exercises session_id = ? AND c_id = ?" => $params),
  2653. 'order' => 'title'
  2654. );
  2655. } else {
  2656. // All exercises
  2657. $conditions = array(
  2658. 'where' => array("$sql_active_exercises (session_id = 0 OR session_id = ? ) AND c_id=?" => $params),
  2659. 'order' => 'title'
  2660. );
  2661. }
  2662. return Database::select('*', $TBL_EXERCISES, $conditions);
  2663. }
  2664. /**
  2665. * Gets the position of the score based in a given score (result/weight)
  2666. * and the exe_id based in the user list
  2667. * (NO Exercises in LPs )
  2668. * @param float $my_score user score to be compared *attention*
  2669. * $my_score = score/weight and not just the score
  2670. * @param int $my_exe_id exe id of the exercise
  2671. * (this is necessary because if 2 students have the same score the one
  2672. * with the minor exe_id will have a best position, just to be fair and FIFO)
  2673. * @param int $exercise_id
  2674. * @param string $course_code
  2675. * @param int $session_id
  2676. * @param array $user_list
  2677. * @param bool $return_string
  2678. *
  2679. * @return int the position of the user between his friends in a course
  2680. * (or course within a session)
  2681. */
  2682. public static function get_exercise_result_ranking(
  2683. $my_score,
  2684. $my_exe_id,
  2685. $exercise_id,
  2686. $course_code,
  2687. $session_id = 0,
  2688. $user_list = array(),
  2689. $return_string = true
  2690. ) {
  2691. //No score given we return
  2692. if (is_null($my_score)) {
  2693. return '-';
  2694. }
  2695. if (empty($user_list)) {
  2696. return '-';
  2697. }
  2698. $best_attempts = array();
  2699. foreach ($user_list as $user_data) {
  2700. $user_id = $user_data['user_id'];
  2701. $best_attempts[$user_id] = self::get_best_attempt_by_user(
  2702. $user_id,
  2703. $exercise_id,
  2704. $course_code,
  2705. $session_id
  2706. );
  2707. }
  2708. if (empty($best_attempts)) {
  2709. return 1;
  2710. } else {
  2711. $position = 1;
  2712. $my_ranking = array();
  2713. foreach ($best_attempts as $user_id => $result) {
  2714. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2715. $my_ranking[$user_id] = $result['exe_result'] / $result['exe_weighting'];
  2716. } else {
  2717. $my_ranking[$user_id] = 0;
  2718. }
  2719. }
  2720. //if (!empty($my_ranking)) {
  2721. asort($my_ranking);
  2722. $position = count($my_ranking);
  2723. if (!empty($my_ranking)) {
  2724. foreach ($my_ranking as $user_id => $ranking) {
  2725. if ($my_score >= $ranking) {
  2726. if ($my_score == $ranking && isset($best_attempts[$user_id]['exe_id'])) {
  2727. $exe_id = $best_attempts[$user_id]['exe_id'];
  2728. if ($my_exe_id < $exe_id) {
  2729. $position--;
  2730. }
  2731. } else {
  2732. $position--;
  2733. }
  2734. }
  2735. }
  2736. }
  2737. //}
  2738. $return_value = array(
  2739. 'position' => $position,
  2740. 'count' => count($my_ranking)
  2741. );
  2742. if ($return_string) {
  2743. if (!empty($position) && !empty($my_ranking)) {
  2744. $return_value = $position.'/'.count($my_ranking);
  2745. } else {
  2746. $return_value = '-';
  2747. }
  2748. }
  2749. return $return_value;
  2750. }
  2751. }
  2752. /**
  2753. * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts
  2754. * (NO Exercises in LPs ) old functionality by attempt
  2755. * @param float user score to be compared attention => score/weight
  2756. * @param int exe id of the exercise
  2757. * (this is necessary because if 2 students have the same score the one
  2758. * with the minor exe_id will have a best position, just to be fair and FIFO)
  2759. * @param int exercise id
  2760. * @param string course code
  2761. * @param int session id
  2762. * @param bool $return_string
  2763. * @return int the position of the user between his friends in a course (or course within a session)
  2764. */
  2765. public static function get_exercise_result_ranking_by_attempt(
  2766. $my_score,
  2767. $my_exe_id,
  2768. $exercise_id,
  2769. $courseId,
  2770. $session_id = 0,
  2771. $return_string = true
  2772. ) {
  2773. if (empty($session_id)) {
  2774. $session_id = 0;
  2775. }
  2776. if (is_null($my_score)) {
  2777. return '-';
  2778. }
  2779. $user_results = Event::get_all_exercise_results(
  2780. $exercise_id,
  2781. $courseId,
  2782. $session_id,
  2783. false
  2784. );
  2785. $position_data = array();
  2786. if (empty($user_results)) {
  2787. return 1;
  2788. } else {
  2789. $position = 1;
  2790. $my_ranking = array();
  2791. foreach ($user_results as $result) {
  2792. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2793. $my_ranking[$result['exe_id']] = $result['exe_result'] / $result['exe_weighting'];
  2794. } else {
  2795. $my_ranking[$result['exe_id']] = 0;
  2796. }
  2797. }
  2798. asort($my_ranking);
  2799. $position = count($my_ranking);
  2800. if (!empty($my_ranking)) {
  2801. foreach ($my_ranking as $exe_id => $ranking) {
  2802. if ($my_score >= $ranking) {
  2803. if ($my_score == $ranking) {
  2804. if ($my_exe_id < $exe_id) {
  2805. $position--;
  2806. }
  2807. } else {
  2808. $position--;
  2809. }
  2810. }
  2811. }
  2812. }
  2813. $return_value = array(
  2814. 'position' => $position,
  2815. 'count' => count($my_ranking)
  2816. );
  2817. if ($return_string) {
  2818. if (!empty($position) && !empty($my_ranking)) {
  2819. return $position.'/'.count($my_ranking);
  2820. }
  2821. }
  2822. return $return_value;
  2823. }
  2824. }
  2825. /**
  2826. * Get the best attempt in a exercise (NO Exercises in LPs )
  2827. * @param int $exercise_id
  2828. * @param int $courseId
  2829. * @param int $session_id
  2830. *
  2831. * @return array
  2832. */
  2833. public static function get_best_attempt_in_course($exercise_id, $courseId, $session_id)
  2834. {
  2835. $user_results = Event::get_all_exercise_results(
  2836. $exercise_id,
  2837. $courseId,
  2838. $session_id,
  2839. false
  2840. );
  2841. $best_score_data = array();
  2842. $best_score = 0;
  2843. if (!empty($user_results)) {
  2844. foreach ($user_results as $result) {
  2845. if (!empty($result['exe_weighting']) &&
  2846. intval($result['exe_weighting']) != 0
  2847. ) {
  2848. $score = $result['exe_result'] / $result['exe_weighting'];
  2849. if ($score >= $best_score) {
  2850. $best_score = $score;
  2851. $best_score_data = $result;
  2852. }
  2853. }
  2854. }
  2855. }
  2856. return $best_score_data;
  2857. }
  2858. /**
  2859. * Get the best score in a exercise (NO Exercises in LPs )
  2860. * @param int $user_id
  2861. * @param int $exercise_id
  2862. * @param int $courseId
  2863. * @param int $session_id
  2864. *
  2865. * @return array
  2866. */
  2867. public static function get_best_attempt_by_user(
  2868. $user_id,
  2869. $exercise_id,
  2870. $courseId,
  2871. $session_id
  2872. ) {
  2873. $user_results = Event::get_all_exercise_results(
  2874. $exercise_id,
  2875. $courseId,
  2876. $session_id,
  2877. false,
  2878. $user_id
  2879. );
  2880. $best_score_data = array();
  2881. $best_score = 0;
  2882. if (!empty($user_results)) {
  2883. foreach ($user_results as $result) {
  2884. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2885. $score = $result['exe_result'] / $result['exe_weighting'];
  2886. if ($score >= $best_score) {
  2887. $best_score = $score;
  2888. $best_score_data = $result;
  2889. }
  2890. }
  2891. }
  2892. }
  2893. return $best_score_data;
  2894. }
  2895. /**
  2896. * Get average score (NO Exercises in LPs )
  2897. * @param int exercise id
  2898. * @param int $courseId
  2899. * @param int session id
  2900. * @return float Average score
  2901. */
  2902. public static function get_average_score($exercise_id, $courseId, $session_id)
  2903. {
  2904. $user_results = Event::get_all_exercise_results(
  2905. $exercise_id,
  2906. $courseId,
  2907. $session_id
  2908. );
  2909. $avg_score = 0;
  2910. if (!empty($user_results)) {
  2911. foreach ($user_results as $result) {
  2912. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2913. $score = $result['exe_result'] / $result['exe_weighting'];
  2914. $avg_score += $score;
  2915. }
  2916. }
  2917. $avg_score = float_format($avg_score / count($user_results), 1);
  2918. }
  2919. return $avg_score;
  2920. }
  2921. /**
  2922. * Get average score by score (NO Exercises in LPs )
  2923. * @param int $courseId
  2924. * @param int session id
  2925. * @return float Average score
  2926. */
  2927. public static function get_average_score_by_course($courseId, $session_id)
  2928. {
  2929. $user_results = Event::get_all_exercise_results_by_course(
  2930. $courseId,
  2931. $session_id,
  2932. false
  2933. );
  2934. $avg_score = 0;
  2935. if (!empty($user_results)) {
  2936. foreach ($user_results as $result) {
  2937. if (!empty($result['exe_weighting']) && intval(
  2938. $result['exe_weighting']
  2939. ) != 0
  2940. ) {
  2941. $score = $result['exe_result'] / $result['exe_weighting'];
  2942. $avg_score += $score;
  2943. }
  2944. }
  2945. // We assume that all exe_weighting
  2946. $avg_score = $avg_score / count($user_results);
  2947. }
  2948. return $avg_score;
  2949. }
  2950. /**
  2951. * @param int $user_id
  2952. * @param int $courseId
  2953. * @param int $session_id
  2954. *
  2955. * @return float|int
  2956. */
  2957. public static function get_average_score_by_course_by_user(
  2958. $user_id,
  2959. $courseId,
  2960. $session_id
  2961. ) {
  2962. $user_results = Event::get_all_exercise_results_by_user(
  2963. $user_id,
  2964. $courseId,
  2965. $session_id
  2966. );
  2967. $avg_score = 0;
  2968. if (!empty($user_results)) {
  2969. foreach ($user_results as $result) {
  2970. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2971. $score = $result['exe_result'] / $result['exe_weighting'];
  2972. $avg_score += $score;
  2973. }
  2974. }
  2975. // We assume that all exe_weighting
  2976. $avg_score = ($avg_score / count($user_results));
  2977. }
  2978. return $avg_score;
  2979. }
  2980. /**
  2981. * Get average score by score (NO Exercises in LPs )
  2982. * @param int exercise id
  2983. * @param int $courseId
  2984. * @param int session id
  2985. * @return float Best average score
  2986. */
  2987. public static function get_best_average_score_by_exercise(
  2988. $exercise_id,
  2989. $courseId,
  2990. $session_id,
  2991. $user_count
  2992. ) {
  2993. $user_results = Event::get_best_exercise_results_by_user(
  2994. $exercise_id,
  2995. $courseId,
  2996. $session_id
  2997. );
  2998. $avg_score = 0;
  2999. if (!empty($user_results)) {
  3000. foreach ($user_results as $result) {
  3001. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  3002. $score = $result['exe_result'] / $result['exe_weighting'];
  3003. $avg_score += $score;
  3004. }
  3005. }
  3006. //We asumme that all exe_weighting
  3007. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  3008. //$avg_score = ($avg_score / count($user_results));
  3009. if (!empty($user_count)) {
  3010. $avg_score = float_format($avg_score / $user_count, 1) * 100;
  3011. } else {
  3012. $avg_score = 0;
  3013. }
  3014. }
  3015. return $avg_score;
  3016. }
  3017. /**
  3018. * Get average score by score (NO Exercises in LPs )
  3019. * @param int exercise id
  3020. * @param int $courseId
  3021. * @param int session id
  3022. * @return float Best average score
  3023. */
  3024. public static function getBestScoreByExercise(
  3025. $exercise_id,
  3026. $courseId,
  3027. $session_id
  3028. ) {
  3029. $user_results = Event::get_best_exercise_results_by_user(
  3030. $exercise_id,
  3031. $courseId,
  3032. $session_id
  3033. );
  3034. $avg_score = 0;
  3035. if (!empty($user_results)) {
  3036. foreach ($user_results as $result) {
  3037. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  3038. $score = $result['exe_result'] / $result['exe_weighting'];
  3039. $avg_score += $score;
  3040. }
  3041. }
  3042. }
  3043. return $avg_score;
  3044. }
  3045. /**
  3046. * @param string $course_code
  3047. * @param int $session_id
  3048. *
  3049. * @return array
  3050. */
  3051. public static function get_exercises_to_be_taken($course_code, $session_id)
  3052. {
  3053. $course_info = api_get_course_info($course_code);
  3054. $exercises = self::get_all_exercises($course_info, $session_id);
  3055. $result = array();
  3056. $now = time() + 15 * 24 * 60 * 60;
  3057. foreach ($exercises as $exercise_item) {
  3058. if (isset($exercise_item['end_time']) &&
  3059. !empty($exercise_item['end_time']) &&
  3060. api_strtotime($exercise_item['end_time'], 'UTC') < $now
  3061. ) {
  3062. $result[] = $exercise_item;
  3063. }
  3064. }
  3065. return $result;
  3066. }
  3067. /**
  3068. * Get student results (only in completed exercises) stats by question
  3069. * @param int $question_id
  3070. * @param int $exercise_id
  3071. * @param string $course_code
  3072. * @param int $session_id
  3073. * @return array
  3074. *
  3075. **/
  3076. public static function get_student_stats_by_question(
  3077. $question_id,
  3078. $exercise_id,
  3079. $course_code,
  3080. $session_id
  3081. ) {
  3082. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  3083. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  3084. $question_id = intval($question_id);
  3085. $exercise_id = intval($exercise_id);
  3086. $course_code = Database::escape_string($course_code);
  3087. $session_id = intval($session_id);
  3088. $courseId = api_get_course_int_id($course_code);
  3089. $sql = "SELECT MAX(marks) as max, MIN(marks) as min, AVG(marks) as average
  3090. FROM $track_exercises e
  3091. INNER JOIN $track_attempt a
  3092. ON (
  3093. a.exe_id = e.exe_id AND
  3094. e.c_id = a.c_id AND
  3095. e.session_id = a.session_id
  3096. )
  3097. WHERE
  3098. exe_exo_id = $exercise_id AND
  3099. a.c_id = $courseId AND
  3100. e.session_id = $session_id AND
  3101. question_id = $question_id AND
  3102. status = ''
  3103. LIMIT 1";
  3104. $result = Database::query($sql);
  3105. $return = array();
  3106. if ($result) {
  3107. $return = Database::fetch_array($result, 'ASSOC');
  3108. }
  3109. return $return;
  3110. }
  3111. /**
  3112. * Get the correct answer count for a fill blanks question
  3113. *
  3114. * @param int $question_id
  3115. * @param int $exercise_id
  3116. * @return int
  3117. */
  3118. public static function getNumberStudentsFillBlanksAnswerCount(
  3119. $question_id,
  3120. $exercise_id
  3121. ) {
  3122. $listStudentsId = [];
  3123. $listAllStudentInfo = CourseManager::get_student_list_from_course_code(
  3124. api_get_course_id(),
  3125. true
  3126. );
  3127. foreach ($listAllStudentInfo as $i => $listStudentInfo) {
  3128. $listStudentsId[] = $listStudentInfo['user_id'];
  3129. }
  3130. $listFillTheBlankResult = FillBlanks::getFillTheBlankTabResult(
  3131. $exercise_id,
  3132. $question_id,
  3133. $listStudentsId,
  3134. '1970-01-01',
  3135. '3000-01-01'
  3136. );
  3137. $arrayCount = [];
  3138. foreach ($listFillTheBlankResult as $resultCount) {
  3139. foreach ($resultCount as $index => $count) {
  3140. //this is only for declare the array index per answer
  3141. $arrayCount[$index] = 0;
  3142. }
  3143. }
  3144. foreach ($listFillTheBlankResult as $resultCount) {
  3145. foreach ($resultCount as $index => $count) {
  3146. $count = ($count === 0) ? 1 : 0;
  3147. $arrayCount[$index] += $count;
  3148. }
  3149. }
  3150. return $arrayCount;
  3151. }
  3152. /**
  3153. * @param int $question_id
  3154. * @param int $exercise_id
  3155. * @param string $course_code
  3156. * @param int $session_id
  3157. * @param string $questionType
  3158. * @return int
  3159. */
  3160. public static function get_number_students_question_with_answer_count(
  3161. $question_id,
  3162. $exercise_id,
  3163. $course_code,
  3164. $session_id,
  3165. $questionType = ''
  3166. ) {
  3167. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  3168. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  3169. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3170. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  3171. $courseUserSession = Database::get_main_table(
  3172. TABLE_MAIN_SESSION_COURSE_USER
  3173. );
  3174. $question_id = intval($question_id);
  3175. $exercise_id = intval($exercise_id);
  3176. $courseId = api_get_course_int_id($course_code);
  3177. $session_id = intval($session_id);
  3178. if ($questionType == FILL_IN_BLANKS) {
  3179. $listStudentsId = array();
  3180. $listAllStudentInfo = CourseManager::get_student_list_from_course_code(
  3181. api_get_course_id(),
  3182. true
  3183. );
  3184. foreach ($listAllStudentInfo as $i => $listStudentInfo) {
  3185. $listStudentsId[] = $listStudentInfo['user_id'];
  3186. }
  3187. $listFillTheBlankResult = FillBlanks::getFillTheBlankTabResult(
  3188. $exercise_id,
  3189. $question_id,
  3190. $listStudentsId,
  3191. '1970-01-01',
  3192. '3000-01-01'
  3193. );
  3194. return FillBlanks::getNbResultFillBlankAll($listFillTheBlankResult);
  3195. }
  3196. if (empty($session_id)) {
  3197. $courseCondition = "
  3198. INNER JOIN $courseUser cu
  3199. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  3200. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = ".STUDENT;
  3201. } else {
  3202. $courseCondition = "
  3203. INNER JOIN $courseUserSession cu
  3204. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  3205. $courseConditionWhere = " AND cu.status = 0 ";
  3206. }
  3207. $sql = "SELECT DISTINCT exe_user_id
  3208. FROM $track_exercises e
  3209. INNER JOIN $track_attempt a
  3210. ON (
  3211. a.exe_id = e.exe_id AND
  3212. e.c_id = a.c_id AND
  3213. e.session_id = a.session_id
  3214. )
  3215. INNER JOIN $courseTable c
  3216. ON (c.id = a.c_id)
  3217. $courseCondition
  3218. WHERE
  3219. exe_exo_id = $exercise_id AND
  3220. a.c_id = $courseId AND
  3221. e.session_id = $session_id AND
  3222. question_id = $question_id AND
  3223. answer <> '0' AND
  3224. e.status = ''
  3225. $courseConditionWhere
  3226. ";
  3227. $result = Database::query($sql);
  3228. $return = 0;
  3229. if ($result) {
  3230. $return = Database::num_rows($result);
  3231. }
  3232. return $return;
  3233. }
  3234. /**
  3235. * @param int $answer_id
  3236. * @param int $question_id
  3237. * @param int $exercise_id
  3238. * @param string $course_code
  3239. * @param int $session_id
  3240. *
  3241. * @return int
  3242. */
  3243. public static function get_number_students_answer_hotspot_count(
  3244. $answer_id,
  3245. $question_id,
  3246. $exercise_id,
  3247. $course_code,
  3248. $session_id
  3249. ) {
  3250. $track_exercises = Database::get_main_table(
  3251. TABLE_STATISTIC_TRACK_E_EXERCISES
  3252. );
  3253. $track_hotspot = Database::get_main_table(
  3254. TABLE_STATISTIC_TRACK_E_HOTSPOT
  3255. );
  3256. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3257. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  3258. $courseUserSession = Database::get_main_table(
  3259. TABLE_MAIN_SESSION_COURSE_USER
  3260. );
  3261. $question_id = intval($question_id);
  3262. $answer_id = intval($answer_id);
  3263. $exercise_id = intval($exercise_id);
  3264. $course_code = Database::escape_string($course_code);
  3265. $session_id = intval($session_id);
  3266. if (empty($session_id)) {
  3267. $courseCondition = "
  3268. INNER JOIN $courseUser cu
  3269. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  3270. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = ".STUDENT;
  3271. } else {
  3272. $courseCondition = "
  3273. INNER JOIN $courseUserSession cu
  3274. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  3275. $courseConditionWhere = " AND cu.status = 0 ";
  3276. }
  3277. $sql = "SELECT DISTINCT exe_user_id
  3278. FROM $track_exercises e
  3279. INNER JOIN $track_hotspot a
  3280. ON (a.hotspot_exe_id = e.exe_id)
  3281. INNER JOIN $courseTable c
  3282. ON (hotspot_course_code = c.code)
  3283. $courseCondition
  3284. WHERE
  3285. exe_exo_id = $exercise_id AND
  3286. a.hotspot_course_code = '$course_code' AND
  3287. e.session_id = $session_id AND
  3288. hotspot_answer_id = $answer_id AND
  3289. hotspot_question_id = $question_id AND
  3290. hotspot_correct = 1 AND
  3291. e.status = ''
  3292. $courseConditionWhere
  3293. ";
  3294. $result = Database::query($sql);
  3295. $return = 0;
  3296. if ($result) {
  3297. $return = Database::num_rows($result);
  3298. }
  3299. return $return;
  3300. }
  3301. /**
  3302. * @param int $answer_id
  3303. * @param int $question_id
  3304. * @param int $exercise_id
  3305. * @param string $course_code
  3306. * @param int $session_id
  3307. * @param string $question_type
  3308. * @param string $correct_answer
  3309. * @param string $current_answer
  3310. * @return int
  3311. */
  3312. public static function get_number_students_answer_count(
  3313. $answer_id,
  3314. $question_id,
  3315. $exercise_id,
  3316. $course_code,
  3317. $session_id,
  3318. $question_type = null,
  3319. $correct_answer = null,
  3320. $current_answer = null
  3321. ) {
  3322. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  3323. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  3324. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  3325. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3326. $courseUserSession = Database::get_main_table(
  3327. TABLE_MAIN_SESSION_COURSE_USER
  3328. );
  3329. $question_id = intval($question_id);
  3330. $answer_id = intval($answer_id);
  3331. $exercise_id = intval($exercise_id);
  3332. $courseId = api_get_course_int_id($course_code);
  3333. $course_code = Database::escape_string($course_code);
  3334. $session_id = intval($session_id);
  3335. switch ($question_type) {
  3336. case FILL_IN_BLANKS:
  3337. $answer_condition = "";
  3338. $select_condition = " e.exe_id, answer ";
  3339. break;
  3340. case MATCHING:
  3341. //no break
  3342. case MATCHING_DRAGGABLE:
  3343. //no break
  3344. default:
  3345. $answer_condition = " answer = $answer_id AND ";
  3346. $select_condition = " DISTINCT exe_user_id ";
  3347. }
  3348. if (empty($session_id)) {
  3349. $courseCondition = "
  3350. INNER JOIN $courseUser cu
  3351. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  3352. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = ".STUDENT;
  3353. } else {
  3354. $courseCondition = "
  3355. INNER JOIN $courseUserSession cu
  3356. ON cu.c_id = a.c_id AND cu.user_id = exe_user_id";
  3357. $courseConditionWhere = " AND cu.status = 0 ";
  3358. }
  3359. $sql = "SELECT $select_condition
  3360. FROM $track_exercises e
  3361. INNER JOIN $track_attempt a
  3362. ON (
  3363. a.exe_id = e.exe_id AND
  3364. e.c_id = a.c_id AND
  3365. e.session_id = a.session_id
  3366. )
  3367. INNER JOIN $courseTable c
  3368. ON c.id = a.c_id
  3369. $courseCondition
  3370. WHERE
  3371. exe_exo_id = $exercise_id AND
  3372. a.c_id = $courseId AND
  3373. e.session_id = $session_id AND
  3374. $answer_condition
  3375. question_id = $question_id AND
  3376. e.status = ''
  3377. $courseConditionWhere
  3378. ";
  3379. $result = Database::query($sql);
  3380. $return = 0;
  3381. if ($result) {
  3382. $good_answers = 0;
  3383. switch ($question_type) {
  3384. case FILL_IN_BLANKS:
  3385. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3386. $fill_blank = self::check_fill_in_blanks(
  3387. $correct_answer,
  3388. $row['answer'],
  3389. $current_answer
  3390. );
  3391. if (isset($fill_blank[$current_answer]) && $fill_blank[$current_answer] == 1) {
  3392. $good_answers++;
  3393. }
  3394. }
  3395. return $good_answers;
  3396. break;
  3397. case MATCHING:
  3398. //no break
  3399. case MATCHING_DRAGGABLE:
  3400. //no break
  3401. default:
  3402. $return = Database::num_rows($result);
  3403. }
  3404. }
  3405. return $return;
  3406. }
  3407. /**
  3408. * @param array $answer
  3409. * @param string $user_answer
  3410. * @return array
  3411. */
  3412. public static function check_fill_in_blanks($answer, $user_answer, $current_answer)
  3413. {
  3414. // the question is encoded like this
  3415. // [A] B [C] D [E] F::10,10,10@1
  3416. // number 1 before the "@" means that is a switchable fill in blank question
  3417. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  3418. // means that is a normal fill blank question
  3419. // first we explode the "::"
  3420. $pre_array = explode('::', $answer);
  3421. // is switchable fill blank or not
  3422. $last = count($pre_array) - 1;
  3423. $is_set_switchable = explode('@', $pre_array[$last]);
  3424. $switchable_answer_set = false;
  3425. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  3426. $switchable_answer_set = true;
  3427. }
  3428. $answer = '';
  3429. for ($k = 0; $k < $last; $k++) {
  3430. $answer .= $pre_array[$k];
  3431. }
  3432. // splits weightings that are joined with a comma
  3433. $answerWeighting = explode(',', $is_set_switchable[0]);
  3434. // we save the answer because it will be modified
  3435. //$temp = $answer;
  3436. $temp = $answer;
  3437. $answer = '';
  3438. $j = 0;
  3439. //initialise answer tags
  3440. $user_tags = $correct_tags = $real_text = array();
  3441. // the loop will stop at the end of the text
  3442. while (1) {
  3443. // quits the loop if there are no more blanks (detect '[')
  3444. if (($pos = api_strpos($temp, '[')) === false) {
  3445. // adds the end of the text
  3446. $answer = $temp;
  3447. $real_text[] = $answer;
  3448. break; //no more "blanks", quit the loop
  3449. }
  3450. // adds the piece of text that is before the blank
  3451. //and ends with '[' into a general storage array
  3452. $real_text[] = api_substr($temp, 0, $pos + 1);
  3453. $answer .= api_substr($temp, 0, $pos + 1);
  3454. //take the string remaining (after the last "[" we found)
  3455. $temp = api_substr($temp, $pos + 1);
  3456. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3457. if (($pos = api_strpos($temp, ']')) === false) {
  3458. // adds the end of the text
  3459. $answer .= $temp;
  3460. break;
  3461. }
  3462. $str = $user_answer;
  3463. preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3464. $str = str_replace('\r\n', '', $str);
  3465. $choices = $arr[1];
  3466. $choice = [];
  3467. $check = false;
  3468. $i = 0;
  3469. foreach ($choices as $item) {
  3470. if ($current_answer === $item) {
  3471. $check = true;
  3472. }
  3473. if ($check) {
  3474. $choice[] = $item;
  3475. $i++;
  3476. }
  3477. if ($i == 3) {
  3478. break;
  3479. }
  3480. }
  3481. $tmp = api_strrpos($choice[$j], ' / ');
  3482. if ($tmp !== false) {
  3483. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3484. }
  3485. $choice[$j] = trim($choice[$j]);
  3486. //Needed to let characters ' and " to work as part of an answer
  3487. $choice[$j] = stripslashes($choice[$j]);
  3488. $user_tags[] = api_strtolower($choice[$j]);
  3489. //put the contents of the [] answer tag into correct_tags[]
  3490. $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  3491. $j++;
  3492. $temp = api_substr($temp, $pos + 1);
  3493. }
  3494. $answer = '';
  3495. $real_correct_tags = $correct_tags;
  3496. $chosen_list = array();
  3497. $good_answer = array();
  3498. for ($i = 0; $i < count($real_correct_tags); $i++) {
  3499. if (!$switchable_answer_set) {
  3500. //needed to parse ' and " characters
  3501. $user_tags[$i] = stripslashes($user_tags[$i]);
  3502. if ($correct_tags[$i] == $user_tags[$i]) {
  3503. $good_answer[$correct_tags[$i]] = 1;
  3504. } elseif (!empty ($user_tags[$i])) {
  3505. $good_answer[$correct_tags[$i]] = 0;
  3506. } else {
  3507. $good_answer[$correct_tags[$i]] = 0;
  3508. }
  3509. } else {
  3510. // switchable fill in the blanks
  3511. if (in_array($user_tags[$i], $correct_tags)) {
  3512. $correct_tags = array_diff($correct_tags, $chosen_list);
  3513. $good_answer[$correct_tags[$i]] = 1;
  3514. } elseif (!empty ($user_tags[$i])) {
  3515. $good_answer[$correct_tags[$i]] = 0;
  3516. } else {
  3517. $good_answer[$correct_tags[$i]] = 0;
  3518. }
  3519. }
  3520. // adds the correct word, followed by ] to close the blank
  3521. $answer .= ' / <font color="green"><b>'.$real_correct_tags[$i].'</b></font>]';
  3522. if (isset ($real_text[$i + 1])) {
  3523. $answer .= $real_text[$i + 1];
  3524. }
  3525. }
  3526. return $good_answer;
  3527. }
  3528. /**
  3529. * @param int $exercise_id
  3530. * @param string $course_code
  3531. * @param int $session_id
  3532. * @return int
  3533. */
  3534. public static function get_number_students_finish_exercise(
  3535. $exercise_id,
  3536. $course_code,
  3537. $session_id
  3538. ) {
  3539. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  3540. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  3541. $exercise_id = intval($exercise_id);
  3542. $course_code = Database::escape_string($course_code);
  3543. $session_id = intval($session_id);
  3544. $sql = "SELECT DISTINCT exe_user_id
  3545. FROM $track_exercises e
  3546. INNER JOIN $track_attempt a
  3547. ON (a.exe_id = e.exe_id)
  3548. WHERE
  3549. exe_exo_id = $exercise_id AND
  3550. course_code = '$course_code' AND
  3551. e.session_id = $session_id AND
  3552. status = ''";
  3553. $result = Database::query($sql);
  3554. $return = 0;
  3555. if ($result) {
  3556. $return = Database::num_rows($result);
  3557. }
  3558. return $return;
  3559. }
  3560. /**
  3561. * @param string $in_name is the name and the id of the <select>
  3562. * @param string $in_default default value for option
  3563. * @param string $in_onchange
  3564. * @return string the html code of the <select>
  3565. */
  3566. public static function displayGroupMenu($in_name, $in_default, $in_onchange = "")
  3567. {
  3568. // check the default value of option
  3569. $tabSelected = array($in_default => " selected='selected' ");
  3570. $res = "";
  3571. $res .= "<select name='$in_name' id='$in_name' onchange='".$in_onchange."' >";
  3572. $res .= "<option value='-1'".$tabSelected["-1"].">-- ".get_lang(
  3573. 'AllGroups'
  3574. )." --</option>";
  3575. $res .= "<option value='0'".$tabSelected["0"].">- ".get_lang(
  3576. 'NotInAGroup'
  3577. )." -</option>";
  3578. $tabGroups = GroupManager::get_group_list();
  3579. $currentCatId = 0;
  3580. for ($i = 0; $i < count($tabGroups); $i++) {
  3581. $tabCategory = GroupManager::get_category_from_group(
  3582. $tabGroups[$i]['iid']
  3583. );
  3584. if ($tabCategory["id"] != $currentCatId) {
  3585. $res .= "<option value='-1' disabled='disabled'>".$tabCategory["title"]."</option>";
  3586. $currentCatId = $tabCategory["id"];
  3587. }
  3588. $res .= "<option ".$tabSelected[$tabGroups[$i]["id"]]."style='margin-left:40px' value='".$tabGroups[$i]["id"]."'>".
  3589. $tabGroups[$i]["name"]."</option>";
  3590. }
  3591. $res .= "</select>";
  3592. return $res;
  3593. }
  3594. /**
  3595. * @param int $exe_id
  3596. */
  3597. public static function create_chat_exercise_session($exe_id)
  3598. {
  3599. if (!isset($_SESSION['current_exercises'])) {
  3600. $_SESSION['current_exercises'] = array();
  3601. }
  3602. $_SESSION['current_exercises'][$exe_id] = true;
  3603. }
  3604. /**
  3605. * @param int $exe_id
  3606. */
  3607. public static function delete_chat_exercise_session($exe_id)
  3608. {
  3609. if (isset($_SESSION['current_exercises'])) {
  3610. $_SESSION['current_exercises'][$exe_id] = false;
  3611. }
  3612. }
  3613. /**
  3614. * Display the exercise results
  3615. * @param Exercise $objExercise
  3616. * @param int $exe_id
  3617. * @param bool $save_user_result save users results (true) or just show the results (false)
  3618. * @param string $remainingMessage
  3619. */
  3620. public static function displayQuestionListByAttempt(
  3621. $objExercise,
  3622. $exe_id,
  3623. $save_user_result = false,
  3624. $remainingMessage = ''
  3625. ) {
  3626. $origin = api_get_origin();
  3627. // Getting attempt info
  3628. $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id(
  3629. $exe_id
  3630. );
  3631. // Getting question list
  3632. $question_list = array();
  3633. if (!empty($exercise_stat_info['data_tracking'])) {
  3634. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  3635. } else {
  3636. // Try getting the question list only if save result is off
  3637. if ($save_user_result == false) {
  3638. $question_list = $objExercise->get_validated_question_list();
  3639. }
  3640. if ($objExercise->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  3641. $question_list = $objExercise->get_validated_question_list();
  3642. }
  3643. }
  3644. $counter = 1;
  3645. $total_score = $total_weight = 0;
  3646. $exercise_content = null;
  3647. // Hide results
  3648. $show_results = false;
  3649. $show_only_score = false;
  3650. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) {
  3651. $show_results = true;
  3652. }
  3653. if (in_array(
  3654. $objExercise->results_disabled,
  3655. array(
  3656. RESULT_DISABLE_SHOW_SCORE_ONLY,
  3657. RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES
  3658. )
  3659. )
  3660. ) {
  3661. $show_only_score = true;
  3662. }
  3663. // Not display expected answer, but score, and feedback
  3664. $show_all_but_expected_answer = false;
  3665. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY &&
  3666. $objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END
  3667. ) {
  3668. $show_all_but_expected_answer = true;
  3669. $show_results = true;
  3670. $show_only_score = false;
  3671. }
  3672. $showTotalScoreAndUserChoicesInLastAttempt = true;
  3673. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT) {
  3674. $show_only_score = true;
  3675. $show_results = true;
  3676. if ($objExercise->attempts > 0) {
  3677. $attempts = Event::getExerciseResultsByUser(
  3678. api_get_user_id(),
  3679. $objExercise->id,
  3680. api_get_course_int_id(),
  3681. api_get_session_id(),
  3682. $exercise_stat_info['orig_lp_id'],
  3683. $exercise_stat_info['orig_lp_item_id'],
  3684. 'desc'
  3685. );
  3686. if ($attempts) {
  3687. $numberAttempts = count($attempts);
  3688. } else {
  3689. $numberAttempts = 0;
  3690. }
  3691. if ($save_user_result) {
  3692. $numberAttempts++;
  3693. }
  3694. if ($numberAttempts >= $objExercise->attempts) {
  3695. $show_results = true;
  3696. $show_only_score = false;
  3697. $showTotalScoreAndUserChoicesInLastAttempt = true;
  3698. } else {
  3699. $showTotalScoreAndUserChoicesInLastAttempt = false;
  3700. }
  3701. }
  3702. }
  3703. if ($show_results || $show_only_score) {
  3704. if (isset($exercise_stat_info['exe_user_id'])) {
  3705. $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
  3706. if ($user_info) {
  3707. // Shows exercise header
  3708. echo $objExercise->show_exercise_result_header(
  3709. $user_info,
  3710. api_convert_and_format_date(
  3711. $exercise_stat_info['start_date'],
  3712. DATE_TIME_FORMAT_LONG
  3713. ),
  3714. $exercise_stat_info['duration'],
  3715. $exercise_stat_info['user_ip']
  3716. );
  3717. }
  3718. }
  3719. }
  3720. // Display text when test is finished #4074 and for LP #4227
  3721. $end_of_message = $objExercise->selectTextWhenFinished();
  3722. if (!empty($end_of_message)) {
  3723. echo Display::return_message($end_of_message, 'normal', false);
  3724. echo "<div class='clear'>&nbsp;</div>";
  3725. }
  3726. $question_list_answers = array();
  3727. $media_list = array();
  3728. $category_list = array();
  3729. $loadChoiceFromSession = false;
  3730. $fromDatabase = true;
  3731. $exerciseResult = null;
  3732. $exerciseResultCoordinates = null;
  3733. $delineationResults = null;
  3734. if ($objExercise->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  3735. $loadChoiceFromSession = true;
  3736. $fromDatabase = false;
  3737. $exerciseResult = Session::read('exerciseResult');
  3738. $exerciseResultCoordinates = Session::read('exerciseResultCoordinates');
  3739. $delineationResults = Session::read('hotspot_delineation_result');
  3740. $delineationResults = isset($delineationResults[$objExercise->id]) ? $delineationResults[$objExercise->id] : null;
  3741. }
  3742. $countPendingQuestions = 0;
  3743. // Loop over all question to show results for each of them, one by one
  3744. if (!empty($question_list)) {
  3745. foreach ($question_list as $questionId) {
  3746. // creates a temporary Question object
  3747. $objQuestionTmp = Question::read($questionId);
  3748. // This variable came from exercise_submit_modal.php
  3749. ob_start();
  3750. $choice = null;
  3751. $delineationChoice = null;
  3752. if ($loadChoiceFromSession) {
  3753. $choice = isset($exerciseResult[$questionId]) ? $exerciseResult[$questionId] : null;
  3754. $delineationChoice = isset($delineationResults[$questionId]) ? $delineationResults[$questionId] : null;
  3755. }
  3756. // We're inside *one* question. Go through each possible answer for this question
  3757. $result = $objExercise->manage_answer(
  3758. $exe_id,
  3759. $questionId,
  3760. $choice,
  3761. 'exercise_result',
  3762. $exerciseResultCoordinates,
  3763. $save_user_result,
  3764. $fromDatabase,
  3765. $show_results,
  3766. $objExercise->selectPropagateNeg(),
  3767. $delineationChoice,
  3768. $showTotalScoreAndUserChoicesInLastAttempt
  3769. );
  3770. if (empty($result)) {
  3771. continue;
  3772. }
  3773. $total_score += $result['score'];
  3774. $total_weight += $result['weight'];
  3775. $question_list_answers[] = array(
  3776. 'question' => $result['open_question'],
  3777. 'answer' => $result['open_answer'],
  3778. 'answer_type' => $result['answer_type']
  3779. );
  3780. $my_total_score = $result['score'];
  3781. $my_total_weight = $result['weight'];
  3782. // Category report
  3783. $category_was_added_for_this_test = false;
  3784. if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) {
  3785. if (!isset($category_list[$objQuestionTmp->category]['score'])) {
  3786. $category_list[$objQuestionTmp->category]['score'] = 0;
  3787. }
  3788. if (!isset($category_list[$objQuestionTmp->category]['total'])) {
  3789. $category_list[$objQuestionTmp->category]['total'] = 0;
  3790. }
  3791. $category_list[$objQuestionTmp->category]['score'] += $my_total_score;
  3792. $category_list[$objQuestionTmp->category]['total'] += $my_total_weight;
  3793. $category_was_added_for_this_test = true;
  3794. }
  3795. if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) {
  3796. foreach ($objQuestionTmp->category_list as $category_id) {
  3797. $category_list[$category_id]['score'] += $my_total_score;
  3798. $category_list[$category_id]['total'] += $my_total_weight;
  3799. $category_was_added_for_this_test = true;
  3800. }
  3801. }
  3802. // No category for this question!
  3803. if ($category_was_added_for_this_test == false) {
  3804. if (!isset($category_list['none']['score'])) {
  3805. $category_list['none']['score'] = 0;
  3806. }
  3807. if (!isset($category_list['none']['total'])) {
  3808. $category_list['none']['total'] = 0;
  3809. }
  3810. $category_list['none']['score'] += $my_total_score;
  3811. $category_list['none']['total'] += $my_total_weight;
  3812. }
  3813. if ($objExercise->selectPropagateNeg() == 0 &&
  3814. $my_total_score < 0
  3815. ) {
  3816. $my_total_score = 0;
  3817. }
  3818. $comnt = null;
  3819. if ($show_results) {
  3820. $comnt = Event::get_comments($exe_id, $questionId);
  3821. $teacherAudio = ExerciseLib::getOralFeedbackAudio(
  3822. $exe_id,
  3823. $questionId,
  3824. api_get_user_id()
  3825. );
  3826. if (!empty($comnt) || $teacherAudio) {
  3827. echo '<b>'.get_lang('Feedback').'</b>';
  3828. }
  3829. if (!empty($comnt)) {
  3830. echo ExerciseLib::getFeedbackText($comnt);
  3831. }
  3832. if ($teacherAudio) {
  3833. echo $teacherAudio;
  3834. }
  3835. }
  3836. if ($show_results) {
  3837. $score = [
  3838. 'result' => self::show_score(
  3839. $my_total_score,
  3840. $my_total_weight,
  3841. false,
  3842. true
  3843. ),
  3844. 'pass' => $my_total_score >= $my_total_weight ? true : false,
  3845. 'score' => $my_total_score,
  3846. 'weight' => $my_total_weight,
  3847. 'comments' => $comnt,
  3848. ];
  3849. } else {
  3850. $score = [];
  3851. }
  3852. if (in_array($objQuestionTmp->type, [FREE_ANSWER, ORAL_EXPRESSION, ANNOTATION])) {
  3853. $check = $objQuestionTmp->isQuestionWaitingReview($score);
  3854. if ($check === false) {
  3855. $countPendingQuestions++;
  3856. }
  3857. }
  3858. $contents = ob_get_clean();
  3859. $question_content = '';
  3860. if ($show_results) {
  3861. $question_content = '<div class="question_row_answer">';
  3862. // Shows question title an description
  3863. $question_content .= $objQuestionTmp->return_header(
  3864. $objExercise,
  3865. $counter,
  3866. $score
  3867. );
  3868. }
  3869. $counter++;
  3870. $question_content .= $contents;
  3871. if ($show_results) {
  3872. $question_content .= '</div>';
  3873. }
  3874. if (!$show_only_score) {
  3875. $exercise_content .= Display::div(Display::panel($question_content),array('class' => 'question-panel'));
  3876. }
  3877. } // end foreach() block that loops over all questions
  3878. }
  3879. $total_score_text = null;
  3880. if ($show_results || $show_only_score) {
  3881. $total_score_text .= '<div class="question_row_score">';
  3882. $total_score_text .= self::getTotalScoreRibbon(
  3883. $objExercise,
  3884. $total_score,
  3885. $total_weight,
  3886. true,
  3887. $countPendingQuestions
  3888. );
  3889. $total_score_text .= '</div>';
  3890. }
  3891. if (!empty($category_list) && ($show_results || $show_only_score)) {
  3892. // Adding total
  3893. $category_list['total'] = array(
  3894. 'score' => $total_score,
  3895. 'total' => $total_weight
  3896. );
  3897. echo TestCategory::get_stats_table_by_attempt(
  3898. $objExercise->id,
  3899. $category_list
  3900. );
  3901. }
  3902. if ($show_all_but_expected_answer) {
  3903. $exercise_content .= "<div class='normal-message'>".get_lang('ExerciseWithFeedbackWithoutCorrectionComment')."</div>";
  3904. }
  3905. // Remove audio auto play from questions on results page - refs BT#7939
  3906. $exercise_content = preg_replace(
  3907. ['/autoplay[\=\".+\"]+/', '/autostart[\=\".+\"]+/'],
  3908. '',
  3909. $exercise_content
  3910. );
  3911. echo $total_score_text;
  3912. echo $exercise_content;
  3913. if (!$show_only_score) {
  3914. echo $total_score_text;
  3915. }
  3916. if (!empty($remainingMessage)) {
  3917. echo Display::return_message($remainingMessage, 'normal', false);
  3918. }
  3919. if ($save_user_result) {
  3920. // Tracking of results
  3921. if ($exercise_stat_info) {
  3922. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  3923. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  3924. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  3925. if (api_is_allowed_to_session_edit()) {
  3926. Event::updateEventExercise(
  3927. $exercise_stat_info['exe_id'],
  3928. $objExercise->selectId(),
  3929. $total_score,
  3930. $total_weight,
  3931. api_get_session_id(),
  3932. $learnpath_id,
  3933. $learnpath_item_id,
  3934. $learnpath_item_view_id,
  3935. $exercise_stat_info['exe_duration'],
  3936. $question_list,
  3937. '',
  3938. array()
  3939. );
  3940. }
  3941. }
  3942. // Send notification at the end
  3943. if (!api_is_allowed_to_edit(null, true) &&
  3944. !api_is_excluded_user_type()
  3945. ) {
  3946. $objExercise->send_mail_notification_for_exam(
  3947. 'end',
  3948. $question_list_answers,
  3949. $origin,
  3950. $exe_id,
  3951. $total_score,
  3952. $total_weight
  3953. );
  3954. }
  3955. }
  3956. }
  3957. /**
  3958. * @param string $class
  3959. * @param string $scoreLabel
  3960. * @param string $result
  3961. *
  3962. * @return string
  3963. */
  3964. public static function getQuestionRibbon($class, $scoreLabel, $result)
  3965. {
  3966. return '<div class="ribbon">
  3967. <div class="rib rib-'.$class.'">
  3968. <h3>'.$scoreLabel.'</h3>
  3969. </div>
  3970. <h4>'.get_lang('Score').': '.$result.'</h4>
  3971. </div>'
  3972. ;
  3973. }
  3974. /**
  3975. * @param Exercise $objExercise
  3976. * @param float $score
  3977. * @param float $weight
  3978. * @param bool $checkPassPercentage
  3979. * @param int $countPendingQuestions
  3980. * @return string
  3981. */
  3982. public static function getTotalScoreRibbon(
  3983. $objExercise,
  3984. $score,
  3985. $weight,
  3986. $checkPassPercentage = false,
  3987. $countPendingQuestions = 0
  3988. ) {
  3989. $passPercentage = $objExercise->selectPassPercentage();
  3990. $ribbon = '<div class="title-score">';
  3991. if ($checkPassPercentage) {
  3992. $isSuccess = self::isSuccessExerciseResult(
  3993. $score,
  3994. $weight,
  3995. $passPercentage
  3996. );
  3997. // Color the final test score if pass_percentage activated
  3998. $class = '';
  3999. if (self::isPassPercentageEnabled($passPercentage)) {
  4000. if ($isSuccess) {
  4001. $class = ' ribbon-total-success';
  4002. } else {
  4003. $class = ' ribbon-total-error';
  4004. }
  4005. }
  4006. $ribbon .= '<div class="total '.$class.'">';
  4007. } else {
  4008. $ribbon .= '<div class="total">';
  4009. }
  4010. $ribbon .= '<h3>'.get_lang('YourTotalScore').":&nbsp;";
  4011. $ribbon .= self::show_score($score, $weight, false, true);
  4012. $ribbon .= '</h3>';
  4013. $ribbon .= '</div>';
  4014. if ($checkPassPercentage) {
  4015. $ribbon .= self::showSuccessMessage(
  4016. $score,
  4017. $weight,
  4018. $passPercentage
  4019. );
  4020. }
  4021. $ribbon .= '</div>';
  4022. if (!empty($countPendingQuestions)) {
  4023. $ribbon .= '<br />';
  4024. $ribbon .= Display::return_message(
  4025. sprintf(
  4026. get_lang('TempScoreXQuestionsNotCorrectedYet'),
  4027. $countPendingQuestions
  4028. ),
  4029. 'warning'
  4030. );
  4031. }
  4032. return $ribbon;
  4033. }
  4034. /**
  4035. * @param int $countLetter
  4036. * @return mixed
  4037. */
  4038. public static function detectInputAppropriateClass($countLetter)
  4039. {
  4040. $limits = array(
  4041. 0 => 'input-mini',
  4042. 10 => 'input-mini',
  4043. 15 => 'input-medium',
  4044. 20 => 'input-xlarge',
  4045. 40 => 'input-xlarge',
  4046. 60 => 'input-xxlarge',
  4047. 100 => 'input-xxlarge',
  4048. 200 => 'input-xxlarge',
  4049. );
  4050. foreach ($limits as $size => $item) {
  4051. if ($countLetter <= $size) {
  4052. return $item;
  4053. }
  4054. }
  4055. return $limits[0];
  4056. }
  4057. /**
  4058. * @param int $senderId
  4059. * @param array $course_info
  4060. * @param string $test
  4061. * @param string $url
  4062. *
  4063. * @return string
  4064. */
  4065. public static function getEmailNotification($senderId, $course_info, $test, $url)
  4066. {
  4067. $teacher_info = api_get_user_info($senderId);
  4068. $from_name = api_get_person_name(
  4069. $teacher_info['firstname'],
  4070. $teacher_info['lastname'],
  4071. null,
  4072. PERSON_NAME_EMAIL_ADDRESS
  4073. );
  4074. $message = '<p>'.get_lang('DearStudentEmailIntroduction').'</p><p>'.get_lang('AttemptVCC');
  4075. $message .= '<h3>'.get_lang('CourseName').'</h3><p>'.Security::remove_XSS($course_info['name']).'';
  4076. $message .= '<h3>'.get_lang('Exercise').'</h3><p>'.Security::remove_XSS($test);
  4077. $message .= '<p>'.get_lang('ClickLinkToViewComment').' <br /><a href="#url#">#url#</a><br />';
  4078. $message .= '<p>'.get_lang('Regards').'</p>';
  4079. $message .= $from_name;
  4080. $message = str_replace("#test#", Security::remove_XSS($test), $message);
  4081. $message = str_replace("#url#", $url, $message);
  4082. return $message;
  4083. }
  4084. /**
  4085. * @return string
  4086. */
  4087. public static function getNotCorrectedYetText()
  4088. {
  4089. return Display::return_message(get_lang('notCorrectedYet'), 'warning');
  4090. }
  4091. /**
  4092. * @param string $message
  4093. * @return string
  4094. */
  4095. public static function getFeedbackText($message)
  4096. {
  4097. // Old style
  4098. //return '<div id="question_feedback">'.$message.'</div>';
  4099. return Display::return_message($message, 'warning', false);
  4100. }
  4101. /**
  4102. * Get the recorder audio component for save a teacher audio feedback
  4103. * @param int $attemptId
  4104. * @param int $questionId
  4105. * @param int $userId
  4106. * @return string
  4107. */
  4108. public static function getOralFeedbackForm($attemptId, $questionId, $userId)
  4109. {
  4110. $view = new Template('', false, false, false, false, false, false);
  4111. $view->assign('user_id', $userId);
  4112. $view->assign('question_id', $questionId);
  4113. $view->assign('directory', "/../exercises/teacher_audio/$attemptId/");
  4114. $view->assign('file_name', "{$questionId}_{$userId}");
  4115. $template = $view->get_template('exercise/oral_expression.tpl');
  4116. return $view->fetch($template);
  4117. }
  4118. /**
  4119. * Get the audio componen for a teacher audio feedback
  4120. * @param int $attemptId
  4121. * @param int $questionId
  4122. * @param int $userId
  4123. * @return string
  4124. */
  4125. public static function getOralFeedbackAudio($attemptId, $questionId, $userId)
  4126. {
  4127. $courseInfo = api_get_course_info();
  4128. $sessionId = api_get_session_id();
  4129. $groupId = api_get_group_id();
  4130. $sysCourseDir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'];
  4131. $webCourseDir = api_get_path(WEB_COURSE_PATH).$courseInfo['path'];
  4132. $fileName = "{$questionId}_{$userId}".DocumentManager::getDocumentSuffix($courseInfo, $sessionId, $groupId);
  4133. $filePath = null;
  4134. $relFilePath = "/exercises/teacher_audio/$attemptId/$fileName";
  4135. if (file_exists($sysCourseDir.$relFilePath.'.ogg')) {
  4136. $filePath = $webCourseDir.$relFilePath.'.ogg';
  4137. } elseif (file_exists($sysCourseDir.$relFilePath.'.wav.wav')) {
  4138. $filePath = $webCourseDir.$relFilePath.'.wav.wav';
  4139. } elseif (file_exists($sysCourseDir.$relFilePath.'.wav')) {
  4140. $filePath = $webCourseDir.$relFilePath.'.wav';
  4141. }
  4142. if (!$filePath) {
  4143. return '';
  4144. }
  4145. return Display::tag(
  4146. 'audio',
  4147. null,
  4148. ['src' => $filePath]
  4149. );
  4150. }
  4151. /**
  4152. * @return array
  4153. */
  4154. public static function getNotificationSettings()
  4155. {
  4156. $emailAlerts = [
  4157. 2 => get_lang('SendEmailToTeacherWhenStudentStartQuiz'),
  4158. 1 => get_lang('SendEmailToTeacherWhenStudentEndQuiz'), // default
  4159. 3 => get_lang('SendEmailToTeacherWhenStudentEndQuizOnlyIfOpenQuestion'),
  4160. 4 => get_lang('SendEmailToTeacherWhenStudentEndQuizOnlyIfOralQuestion')
  4161. ];
  4162. return $emailAlerts;
  4163. }
  4164. }