exercise.lib.php 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795
  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 int $questionId question id
  18. * @param bool $only_questions if true only show the questions, no exercise title
  19. * @param bool $origin i.e = learnpath
  20. * @param string $current_item current item from the list of questions
  21. * @param bool $show_title
  22. * @param bool $freeze
  23. * @param array $user_choice
  24. * @param bool $show_comment
  25. * @param bool $exercise_feedback
  26. * @param bool $show_answers
  27. * */
  28. public static function showQuestion(
  29. $questionId,
  30. $only_questions = false,
  31. $origin = false,
  32. $current_item = '',
  33. $show_title = true,
  34. $freeze = false,
  35. $user_choice = array(),
  36. $show_comment = false,
  37. $exercise_feedback = null,
  38. $show_answers = false
  39. ) {
  40. // Change false to true in the following line to enable answer hinting
  41. $debug_mark_answer = $show_answers;
  42. // Reads question information
  43. if (!$objQuestionTmp = Question::read($questionId)) {
  44. // Question not found
  45. return false;
  46. }
  47. if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) {
  48. $show_comment = false;
  49. }
  50. $answerType = $objQuestionTmp->selectType();
  51. $pictureName = $objQuestionTmp->selectPicture();
  52. $s = '';
  53. if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
  54. // Question is not a hotspot
  55. if (!$only_questions) {
  56. $questionDescription = $objQuestionTmp->selectDescription();
  57. if ($show_title) {
  58. TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
  59. echo Display::div(
  60. $current_item . '. ' . $objQuestionTmp->selectTitle(),
  61. array('class' => 'question_title')
  62. );
  63. }
  64. if (!empty($questionDescription)) {
  65. echo Display::div(
  66. $questionDescription,
  67. array('class' => 'question_description')
  68. );
  69. }
  70. }
  71. if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) &&
  72. $freeze
  73. ) {
  74. return '';
  75. }
  76. echo '<div class="question_options row">';
  77. // construction of the Answer object (also gets all answers details)
  78. $objAnswerTmp = new Answer($questionId);
  79. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  80. $course_id = api_get_course_int_id();
  81. $quiz_question_options = Question::readQuestionOption(
  82. $questionId,
  83. $course_id
  84. );
  85. // For "matching" type here, we need something a little bit special
  86. // because the match between the suggestions and the answers cannot be
  87. // done easily (suggestions and answers are in the same table), so we
  88. // have to go through answers first (elems with "correct" value to 0).
  89. $select_items = array();
  90. //This will contain the number of answers on the left side. We call them
  91. // suggestions here, for the sake of comprehensions, while the ones
  92. // on the right side are called answers
  93. $num_suggestions = 0;
  94. if (in_array($answerType, [MATCHING, DRAGGABLE])) {
  95. if ($answerType == DRAGGABLE) {
  96. $s .= '<div class="ui-widget ui-helper-clearfix">
  97. <div class="clearfix">
  98. <ul class="exercise-draggable-answer ui-helper-reset ui-helper-clearfix">';
  99. } else {
  100. $s .= '<table class="table table-hover table-striped">';
  101. }
  102. // Iterate through answers
  103. $x = 1;
  104. //mark letters for each answer
  105. $letter = 'A';
  106. $answer_matching = array();
  107. $cpt1 = array();
  108. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  109. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  110. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  111. $answer = $objAnswerTmp->selectAnswer($answerId);
  112. if ($answerCorrect == 0) {
  113. // options (A, B, C, ...) that will be put into the list-box
  114. // have the "correct" field set to 0 because they are answer
  115. $cpt1[$x] = $letter;
  116. $answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId(
  117. $numAnswer
  118. );
  119. $x++;
  120. $letter++;
  121. }
  122. }
  123. $i = 1;
  124. $select_items[0]['id'] = 0;
  125. $select_items[0]['letter'] = '--';
  126. $select_items[0]['answer'] = '';
  127. foreach ($answer_matching as $id => $value) {
  128. $select_items[$i]['id'] = $value['id'];
  129. $select_items[$i]['letter'] = $cpt1[$id];
  130. $select_items[$i]['answer'] = $value['answer'];
  131. $i++;
  132. }
  133. $user_choice_array_position = array();
  134. if (!empty($user_choice)) {
  135. foreach ($user_choice as $item) {
  136. $user_choice_array_position[$item['position']] = $item['answer'];
  137. }
  138. }
  139. $num_suggestions = ($nbrAnswers - $x) + 1;
  140. } elseif ($answerType == FREE_ANSWER) {
  141. $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer'] : null;
  142. $form = new FormValidator('free_choice_'.$questionId);
  143. $config = array(
  144. 'ToolbarSet' => 'TestFreeAnswer'
  145. );
  146. $form->addHtmlEditor("choice[" . $questionId . "]", null, false, false, $config);
  147. $form->setDefaults(array("choice[" . $questionId . "]" => $fck_content));
  148. $s .= $form->returnForm();
  149. } elseif ($answerType == ORAL_EXPRESSION) {
  150. // Add nanog
  151. if (api_get_setting('enable_nanogong') == 'true') {
  152. //@todo pass this as a parameter
  153. global $exercise_stat_info, $exerciseId, $exe_id;
  154. if (!empty($exercise_stat_info)) {
  155. $params = array(
  156. 'exercise_id' => $exercise_stat_info['exe_exo_id'],
  157. 'exe_id' => $exercise_stat_info['exe_id'],
  158. 'question_id' => $questionId
  159. );
  160. } else {
  161. $params = array(
  162. 'exercise_id' => $exerciseId,
  163. 'exe_id' => 'temp_exe',
  164. 'question_id' => $questionId
  165. );
  166. }
  167. $nano = new Nanogong($params);
  168. echo $nano->show_button();
  169. }
  170. $form = new FormValidator('free_choice_'.$questionId);
  171. $config = array(
  172. 'ToolbarSet' => 'TestFreeAnswer'
  173. );
  174. $form->addHtmlEditor("choice[" . $questionId . "]", null, false, false, $config);
  175. //$form->setDefaults(array("choice[" . $questionId . "]" => $fck_content));
  176. $s .= $form->return_form();
  177. }
  178. // Now navigate through the possible answers, using the max number of
  179. // answers for the question as a limiter
  180. $lines_count = 1; // a counter for matching-type answers
  181. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  182. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  183. ) {
  184. $header = Display::tag('th', get_lang('Options'));
  185. foreach ($objQuestionTmp->options as $item) {
  186. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  187. if (in_array($item, $objQuestionTmp->options)) {
  188. $header .= Display::tag('th', get_lang($item));
  189. } else {
  190. $header .= Display::tag('th', $item);
  191. }
  192. } else {
  193. $header .= Display::tag('th', $item);
  194. }
  195. }
  196. if ($show_comment) {
  197. $header .= Display::tag('th', get_lang('Feedback'));
  198. }
  199. $s .= '<table class="table table-hover table-striped">';
  200. $s .= Display::tag(
  201. 'tr',
  202. $header,
  203. array('style' => 'text-align:left;')
  204. );
  205. }
  206. if ($show_comment) {
  207. if (
  208. in_array(
  209. $answerType,
  210. array(
  211. MULTIPLE_ANSWER,
  212. MULTIPLE_ANSWER_COMBINATION,
  213. UNIQUE_ANSWER,
  214. UNIQUE_ANSWER_IMAGE,
  215. UNIQUE_ANSWER_NO_OPTION,
  216. GLOBAL_MULTIPLE_ANSWER
  217. )
  218. )
  219. ) {
  220. $header = Display::tag('th', get_lang('Options'));
  221. if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) {
  222. $header .= Display::tag('th', get_lang('Feedback'));
  223. }
  224. $s .= '<table class="table table-hover table-striped">';
  225. $s .= Display::tag(
  226. 'tr',
  227. $header,
  228. array('style' => 'text-align:left;')
  229. );
  230. }
  231. }
  232. $matching_correct_answer = 0;
  233. $user_choice_array = array();
  234. if (!empty($user_choice)) {
  235. foreach ($user_choice as $item) {
  236. $user_choice_array[] = $item['answer'];
  237. }
  238. }
  239. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  240. $answer = $objAnswerTmp->selectAnswer($answerId);
  241. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  242. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  243. $comment = $objAnswerTmp->selectComment($answerId);
  244. $attributes = array();
  245. // Unique answer
  246. if (in_array($answerType, [UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, UNIQUE_ANSWER_IMAGE])) {
  247. $input_id = 'choice-' . $questionId . '-' . $answerId;
  248. if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer) {
  249. $attributes = array(
  250. 'id' => $input_id,
  251. 'checked' => 1,
  252. 'selected' => 1
  253. );
  254. } else {
  255. $attributes = array('id' => $input_id);
  256. }
  257. if ($debug_mark_answer) {
  258. if ($answerCorrect) {
  259. $attributes['checked'] = 1;
  260. $attributes['selected'] = 1;
  261. }
  262. }
  263. if ($show_comment) {
  264. $s .= '<tr><td>';
  265. }
  266. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  267. if ($show_comment) {
  268. if (empty($comment)) {
  269. $s .= '<div id="answer' . $questionId . $numAnswer . '" '
  270. . 'class="exercise-unique-answer-image col-xs-6" style="text-align: center">';
  271. } else {
  272. $s .= '<div id="answer' . $questionId . $numAnswer . '" '
  273. . 'class="exercise-unique-answer-image col-xs-6 col-sm-12" style="text-align: center">';
  274. }
  275. } else {
  276. $s .= '<div id="answer' . $questionId . $numAnswer . '" '
  277. . 'class="exercise-unique-answer-image col-xs-6 col-md-4" style="text-align: center">';
  278. }
  279. }
  280. $answer = Security::remove_XSS($answer, STUDENT);
  281. $s .= Display::input(
  282. 'hidden',
  283. 'choice2[' . $questionId . ']',
  284. '0'
  285. );
  286. $answer_input = null;
  287. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  288. $attributes['style'] = 'display: none;';
  289. $answer = '<div class="thumbnail">' . $answer . '</div>';
  290. }
  291. $answer_input .= '<label class="radio">';
  292. $answer_input .= Display::input(
  293. 'radio',
  294. 'choice[' . $questionId . ']',
  295. $numAnswer,
  296. $attributes
  297. );
  298. $answer_input .= $answer;
  299. $answer_input .= '</label>';
  300. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  301. $answer_input .= "</div>";
  302. }
  303. if ($show_comment) {
  304. $s .= $answer_input;
  305. $s .= '</td>';
  306. $s .= '<td>';
  307. $s .= $comment;
  308. $s .= '</td>';
  309. $s .= '</tr>';
  310. } else {
  311. $s .= $answer_input;
  312. }
  313. } elseif (
  314. $answerType == MULTIPLE_ANSWER ||
  315. $answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  316. $answerType == GLOBAL_MULTIPLE_ANSWER
  317. ) {
  318. $input_id = 'choice-' . $questionId . '-' . $answerId;
  319. $answer = Security::remove_XSS($answer, STUDENT);
  320. if (in_array($numAnswer, $user_choice_array)) {
  321. $attributes = array(
  322. 'id' => $input_id,
  323. 'checked' => 1,
  324. 'selected' => 1
  325. );
  326. } else {
  327. $attributes = array('id' => $input_id);
  328. }
  329. if ($debug_mark_answer) {
  330. if ($answerCorrect) {
  331. $attributes['checked'] = 1;
  332. $attributes['selected'] = 1;
  333. }
  334. }
  335. if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  336. $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
  337. $answer_input = '<label class="checkbox">';
  338. $answer_input .= Display::input(
  339. 'checkbox',
  340. 'choice[' . $questionId . '][' . $numAnswer . ']',
  341. $numAnswer,
  342. $attributes
  343. );
  344. $answer_input .= $answer;
  345. $answer_input .= '</label>';
  346. if ($show_comment) {
  347. $s .= '<tr><td>';
  348. $s .= $answer_input;
  349. $s .= '</td>';
  350. $s .= '<td>';
  351. $s .= $comment;
  352. $s .= '</td>';
  353. $s .= '</tr>';
  354. } else {
  355. $s .= $answer_input;
  356. }
  357. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  358. $my_choice = array();
  359. if (!empty($user_choice_array)) {
  360. foreach ($user_choice_array as $item) {
  361. $item = explode(':', $item);
  362. $my_choice[$item[0]] = $item[1];
  363. }
  364. }
  365. $s .= '<tr>';
  366. $s .= Display::tag('td', $answer);
  367. if (!empty($quiz_question_options)) {
  368. foreach ($quiz_question_options as $id => $item) {
  369. if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
  370. $attributes = array(
  371. 'checked' => 1,
  372. 'selected' => 1
  373. );
  374. } else {
  375. $attributes = array();
  376. }
  377. if ($debug_mark_answer) {
  378. if ($id == $answerCorrect) {
  379. $attributes['checked'] = 1;
  380. $attributes['selected'] = 1;
  381. }
  382. }
  383. $s .= Display::tag(
  384. 'td',
  385. Display::input(
  386. 'radio',
  387. 'choice[' . $questionId . '][' . $numAnswer . ']',
  388. $id,
  389. $attributes
  390. ),
  391. array('style' => '')
  392. );
  393. }
  394. }
  395. if ($show_comment) {
  396. $s .= '<td>';
  397. $s .= $comment;
  398. $s .= '</td>';
  399. }
  400. $s .= '</tr>';
  401. }
  402. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  403. // multiple answers
  404. $input_id = 'choice-' . $questionId . '-' . $answerId;
  405. if (in_array($numAnswer, $user_choice_array)) {
  406. $attributes = array(
  407. 'id' => $input_id,
  408. 'checked' => 1,
  409. 'selected' => 1
  410. );
  411. } else {
  412. $attributes = array('id' => $input_id);
  413. }
  414. if ($debug_mark_answer) {
  415. if ($answerCorrect) {
  416. $attributes['checked'] = 1;
  417. $attributes['selected'] = 1;
  418. }
  419. }
  420. $answer = Security::remove_XSS($answer, STUDENT);
  421. $answer_input = '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
  422. $answer_input .= '<label class="checkbox">';
  423. $answer_input .= Display::input(
  424. 'checkbox',
  425. 'choice[' . $questionId . '][' . $numAnswer . ']',
  426. 1,
  427. $attributes
  428. );
  429. $answer_input .= $answer;
  430. $answer_input .= '</label>';
  431. if ($show_comment) {
  432. $s .= '<tr>';
  433. $s .= '<td>';
  434. $s .= $answer_input;
  435. $s .= '</td>';
  436. $s .= '<td>';
  437. $s .= $comment;
  438. $s .= '</td>';
  439. $s .= '</tr>';
  440. } else {
  441. $s .= $answer_input;
  442. }
  443. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  444. $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
  445. $my_choice = array();
  446. if (!empty($user_choice_array)) {
  447. foreach ($user_choice_array as $item) {
  448. $item = explode(':', $item);
  449. $my_choice[$item[0]] = $item[1];
  450. }
  451. }
  452. $answer = Security::remove_XSS($answer, STUDENT);
  453. $s .= '<tr>';
  454. $s .= Display::tag('td', $answer);
  455. foreach ($objQuestionTmp->options as $key => $item) {
  456. if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
  457. $attributes = array(
  458. 'checked' => 1,
  459. 'selected' => 1
  460. );
  461. } else {
  462. $attributes = array();
  463. }
  464. if ($debug_mark_answer) {
  465. if ($key == $answerCorrect) {
  466. $attributes['checked'] = 1;
  467. $attributes['selected'] = 1;
  468. }
  469. }
  470. $s .= Display::tag(
  471. 'td',
  472. Display::input(
  473. 'radio',
  474. 'choice[' . $questionId . '][' . $numAnswer . ']',
  475. $key,
  476. $attributes
  477. )
  478. );
  479. }
  480. if ($show_comment) {
  481. $s .= '<td>';
  482. $s .= $comment;
  483. $s .= '</td>';
  484. }
  485. $s .= '</tr>';
  486. } elseif ($answerType == FILL_IN_BLANKS) {
  487. /*
  488. * In the FILL_IN_BLANKS test
  489. * you mustn't have [ and ] in the textarea
  490. * you mustn't have :: in the textarea
  491. * the text to find mustn't be empty or contains only spaces
  492. * the text to find mustn't contains HTML tags
  493. * the text to find mustn't contains char "
  494. */
  495. list($answer) = explode('::', $answer);
  496. // $correct_answer_list array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
  497. api_preg_match_all(
  498. '/\[[^]]+\]/',
  499. $answer,
  500. $correct_answer_list
  501. );
  502. // get student answer to display it if student go back to previous fillBlank answer question in a test
  503. if (isset($user_choice[0]['answer'])) {
  504. api_preg_match_all(
  505. '/\[[^]]+\]/',
  506. $user_choice[0]['answer'],
  507. $student_answer_list
  508. );
  509. $student_answer_list_tobecleaned = $student_answer_list[0];
  510. $student_answer_list = array();
  511. // here we got the student answer in a test
  512. // let's clean up the results
  513. /*
  514. Array
  515. (
  516. [0] => Array
  517. (
  518. [0] => [<font color="red"><s>yer</s></font> / <font color="green"><b>ici</b></font>]
  519. [1] => [<font color="red"><s>plop</s></font> / <font color="green"><b>/p</b></font>]
  520. )
  521. )
  522. */
  523. for ($i = 0; $i < count(
  524. $student_answer_list_tobecleaned
  525. ); $i++) {
  526. $answer_corrected = $student_answer_list_tobecleaned[$i];
  527. /*
  528. * we got if student answer is wrong
  529. * [<font color="red"><s>rrr</s></font> / <font color="green"><b>/p</b></font>]
  530. * or if student answer is good
  531. * [plop / <font color="green"><b>plop</b></font>]
  532. * or if student didn't answer []
  533. */
  534. $answer_corrected = api_preg_replace(
  535. '| / <font color="green"><b>.*$|',
  536. '',
  537. $answer_corrected
  538. );
  539. /*
  540. * we got [<font color="red"><s>rrr</s></font> or [plop or [
  541. */
  542. $answer_corrected = api_preg_replace(
  543. '/^\[/',
  544. '',
  545. $answer_corrected
  546. );
  547. /*
  548. * we got <font color="red"><s>rrr</s></font> or plop
  549. * non breakable spaces &nbsp;&nbsp;&nbsp; from /main/exercice/exercise.class.php have been removed l 2391 and l 2370
  550. */
  551. $answer_corrected = api_preg_replace(
  552. '|^<font color="red"><s>|',
  553. '',
  554. $answer_corrected
  555. );
  556. $answer_corrected = api_preg_replace(
  557. '|</s></font>$|',
  558. '',
  559. $answer_corrected
  560. );
  561. $answer_corrected = '[' . $answer_corrected . ']';
  562. /*
  563. * we got [rrr] or [plop] or []
  564. */
  565. $student_answer_list[] = $answer_corrected;
  566. }
  567. }
  568. // If display preview of answer in test view for exemple, set the student answer to the correct answers
  569. if ($debug_mark_answer) {
  570. // contain the rights answers surronded with brackets
  571. $student_answer_list = $correct_answer_list[0];
  572. }
  573. /*
  574. Split the response by bracket
  575. tab_comments is an array with text surrounding the text to find
  576. we add a space before and after the answer_question to be sure to
  577. have a block of text before and after [xxx] patterns
  578. so we have n text to find ([xxx]) and n+1 block of texts before,
  579. between and after the text to find
  580. */
  581. $tab_comments = api_preg_split(
  582. '/\[[^]]+\]/',
  583. ' ' . $answer . ' '
  584. );
  585. if (!empty($correct_answer_list) && !empty($student_answer_list)) {
  586. $answer = "";
  587. $i = 0;
  588. foreach ($student_answer_list as $student_item) {
  589. // remove surronding brackets
  590. $student_response = api_substr(
  591. $student_item,
  592. 1,
  593. api_strlen($student_item) - 2
  594. );
  595. $size = strlen($student_item);
  596. $attributes['class'] = self::detectInputAppropriateClass(
  597. $size
  598. );
  599. $answer .= $tab_comments[$i] .
  600. Display::input(
  601. 'text',
  602. "choice[$questionId][]",
  603. $student_response,
  604. $attributes
  605. );
  606. $i++;
  607. }
  608. $answer .= $tab_comments[$i];
  609. } else {
  610. // display exercise with empty input fields
  611. // every [xxx] are replaced with an empty input field
  612. foreach ($correct_answer_list[0] as $item) {
  613. $size = strlen($item);
  614. $attributes['class'] = self::detectInputAppropriateClass(
  615. $size
  616. );
  617. $attributes['class'] .= ' block_on_enter';
  618. $answer = str_replace(
  619. $item,
  620. Display::input(
  621. 'text',
  622. "choice[$questionId][]",
  623. '',
  624. $attributes
  625. ),
  626. $answer
  627. );
  628. }
  629. /*$answer = api_preg_replace(
  630. '/\[[^]]+\]/',
  631. Display::input(
  632. 'text',
  633. "choice[$questionId][]",
  634. '',
  635. $attributes
  636. ), $answer);*/
  637. }
  638. $s .= $answer;
  639. } elseif ($answerType == CALCULATED_ANSWER) {
  640. /*
  641. * In the CALCULATED_ANSWER test
  642. * you mustn't have [ and ] in the textarea
  643. * you mustn't have @@ in the textarea
  644. * the text to find mustn't be empty or contains only spaces
  645. * the text to find mustn't contains HTML tags
  646. * the text to find mustn't contains char "
  647. */
  648. if ($origin !== null) {
  649. global $exe_id;
  650. $trackAttempts = Database::get_main_table(
  651. TABLE_STATISTIC_TRACK_E_ATTEMPT
  652. );
  653. $sqlTrackAttempt = 'SELECT answer FROM ' . $trackAttempts . ' WHERE exe_id=' . $exe_id . ' AND question_id=' . $questionId;
  654. $rsLastAttempt = Database::query($sqlTrackAttempt);
  655. $rowLastAttempt = Database::fetch_array($rsLastAttempt);
  656. $answer = $rowLastAttempt['answer'];
  657. if (empty($answer)) {
  658. $_SESSION['calculatedAnswerId'][$questionId] = mt_rand(
  659. 1,
  660. $nbrAnswers
  661. );
  662. $answer = $objAnswerTmp->selectAnswer(
  663. $_SESSION['calculatedAnswerId'][$questionId]
  664. );
  665. }
  666. }
  667. list($answer) = explode('@@', $answer);
  668. // $correctAnswerList array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
  669. api_preg_match_all(
  670. '/\[[^]]+\]/',
  671. $answer,
  672. $correctAnswerList
  673. );
  674. // get student answer to display it if student go back to previous calculated answer question in a test
  675. if (isset($user_choice[0]['answer'])) {
  676. api_preg_match_all(
  677. '/\[[^]]+\]/',
  678. $answer,
  679. $studentAnswerList
  680. );
  681. $studentAnswerListTobecleaned = $studentAnswerList[0];
  682. $studentAnswerList = array();
  683. for ($i = 0; $i < count(
  684. $studentAnswerListTobecleaned
  685. ); $i++) {
  686. $answerCorrected = $studentAnswerListTobecleaned[$i];
  687. $answerCorrected = api_preg_replace(
  688. '| / <font color="green"><b>.*$|',
  689. '',
  690. $answerCorrected
  691. );
  692. $answerCorrected = api_preg_replace(
  693. '/^\[/',
  694. '',
  695. $answerCorrected
  696. );
  697. $answerCorrected = api_preg_replace(
  698. '|^<font color="red"><s>|',
  699. '',
  700. $answerCorrected
  701. );
  702. $answerCorrected = api_preg_replace(
  703. '|</s></font>$|',
  704. '',
  705. $answerCorrected
  706. );
  707. $answerCorrected = '[' . $answerCorrected . ']';
  708. $studentAnswerList[] = $answerCorrected;
  709. }
  710. }
  711. // If display preview of answer in test view for exemple, set the student answer to the correct answers
  712. if ($debug_mark_answer) {
  713. // contain the rights answers surronded with brackets
  714. $studentAnswerList = $correctAnswerList[0];
  715. }
  716. /*
  717. Split the response by bracket
  718. tabComments is an array with text surrounding the text to find
  719. we add a space before and after the answerQuestion to be sure to
  720. have a block of text before and after [xxx] patterns
  721. so we have n text to find ([xxx]) and n+1 block of texts before,
  722. between and after the text to find
  723. */
  724. $tabComments = api_preg_split(
  725. '/\[[^]]+\]/',
  726. ' ' . $answer . ' '
  727. );
  728. if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
  729. $answer = "";
  730. $i = 0;
  731. foreach ($studentAnswerList as $studentItem) {
  732. // remove surronding brackets
  733. $studentResponse = api_substr(
  734. $studentItem,
  735. 1,
  736. api_strlen($studentItem) - 2
  737. );
  738. $size = strlen($studentItem);
  739. $attributes['class'] = self::detectInputAppropriateClass(
  740. $size
  741. );
  742. $answer .= $tabComments[$i] .
  743. Display::input(
  744. 'text',
  745. "choice[$questionId][]",
  746. $studentResponse,
  747. $attributes
  748. );
  749. $i++;
  750. }
  751. $answer .= $tabComments[$i];
  752. } else {
  753. // display exercise with empty input fields
  754. // every [xxx] are replaced with an empty input field
  755. foreach ($correctAnswerList[0] as $item) {
  756. $size = strlen($item);
  757. $attributes['class'] = self::detectInputAppropriateClass(
  758. $size
  759. );
  760. $answer = str_replace(
  761. $item,
  762. Display::input(
  763. 'text',
  764. "choice[$questionId][]",
  765. '',
  766. $attributes
  767. ),
  768. $answer
  769. );
  770. }
  771. }
  772. if ($origin !== null) {
  773. $s = $answer;
  774. break;
  775. } else {
  776. $s .= $answer;
  777. }
  778. } elseif ($answerType == MATCHING) {
  779. // matching type, showing suggestions and answers
  780. // TODO: replace $answerId by $numAnswer
  781. if ($answerCorrect != 0) {
  782. // only show elements to be answered (not the contents of
  783. // the select boxes, who are corrrect = 0)
  784. $s .= '<tr><td width="45%" valign="top">';
  785. $parsed_answer = $answer;
  786. //left part questions
  787. $s .= ' <span style="float:left; width:8%;"><b>' . $lines_count . '</b>.&nbsp;</span>
  788. <span style="float:left; width:92%;">' . $parsed_answer . '</span></td>';
  789. //middle part (matches selects)
  790. $s .= '<td width="10%" valign="top" align="center">&nbsp;&nbsp;
  791. <select name="choice[' . $questionId . '][' . $numAnswer . ']">';
  792. // fills the list-box
  793. foreach ($select_items as $key => $val) {
  794. // set $debug_mark_answer to true at function start to
  795. // show the correct answer with a suffix '-x'
  796. $selected = '';
  797. if ($debug_mark_answer) {
  798. if ($val['id'] == $answerCorrect) {
  799. $selected = 'selected="selected"';
  800. }
  801. }
  802. //$user_choice_array_position
  803. if (isset($user_choice_array_position[$numAnswer]) && $val['id'] == $user_choice_array_position[$numAnswer]) {
  804. $selected = 'selected="selected"';
  805. }
  806. /*if (isset($user_choice_array[$matching_correct_answer]) && $val['id'] == $user_choice_array[$matching_correct_answer]['answer']) {
  807. $selected = 'selected="selected"';
  808. }*/
  809. $s .= '<option value="' . $val['id'] . '" ' . $selected . '>' . $val['letter'] . '</option>';
  810. } // end foreach()
  811. $s .= '</select></td>';
  812. $s .= '<td width="45%" valign="top" >';
  813. if (isset($select_items[$lines_count])) {
  814. $s .= '<span style="float:left; width:5%;"><b>' . $select_items[$lines_count]['letter'] . '.</b></span>' .
  815. '<span style="float:left; width:95%;">' . $select_items[$lines_count]['answer'] . '</span>';
  816. } else {
  817. $s .= '&nbsp;';
  818. }
  819. $s .= '</td>';
  820. $s .= '</tr>';
  821. $lines_count++;
  822. //if the left side of the "matching" has been completely
  823. // shown but the right side still has values to show...
  824. if (($lines_count - 1) == $num_suggestions) {
  825. // if it remains answers to shown at the right side
  826. while (isset($select_items[$lines_count])) {
  827. $s .= '<tr>
  828. <td colspan="2"></td>
  829. <td valign="top">';
  830. $s .= '<b>' . $select_items[$lines_count]['letter'] . '.</b> ' . $select_items[$lines_count]['answer'];
  831. $s .= "</td>
  832. </tr>";
  833. $lines_count++;
  834. } // end while()
  835. } // end if()
  836. $matching_correct_answer++;
  837. }
  838. } elseif ($answerType == DRAGGABLE) {
  839. if ($answerCorrect != 0) {
  840. $parsed_answer = $answer;
  841. $windowId = $questionId . '_' . $lines_count;
  842. $s .= '<li class="thumbnail" id="' . $windowId . '">';
  843. $s .= Display::div(
  844. $parsed_answer,
  845. [
  846. 'id' => "window_$windowId",
  847. 'class' => "window{$questionId}_question_draggable exercise-draggable-answer-option"
  848. ]
  849. );
  850. $selectedValue = 0;
  851. $draggableSelectOptions = [];
  852. foreach ($select_items as $key => $val) {
  853. if ($debug_mark_answer) {
  854. if ($val['id'] == $answerCorrect) {
  855. $selectedValue = $val['id'];
  856. }
  857. }
  858. if (
  859. isset($user_choice[$matching_correct_answer]) &&
  860. $val['id'] == $user_choice[$matching_correct_answer]['answer']
  861. ) {
  862. $selectedValue = $val['id'];
  863. }
  864. $draggableSelectOptions[$val['id']] = $val['letter'];
  865. }
  866. $s .= Display::select(
  867. "choice[$questionId][$numAnswer]",
  868. $draggableSelectOptions,
  869. $selectedValue,
  870. [
  871. 'id' => "window_{$windowId}_select",
  872. 'class' => 'select_option',
  873. 'style' => 'display: none;'
  874. ],
  875. false
  876. );
  877. if (!empty($answerCorrect) && !empty($selectedValue)) {
  878. $s .= <<<JAVASCRIPT
  879. <script>
  880. $(function() {
  881. DraggableAnswer.deleteItem(
  882. $('#{$questionId}_{$selectedValue}'),
  883. $('#drop_$windowId')
  884. );
  885. });
  886. </script>
  887. JAVASCRIPT;
  888. }
  889. if (isset($select_items[$lines_count])) {
  890. $s .= Display::div(
  891. Display::tag(
  892. 'b',
  893. $select_items[$lines_count]['letter']
  894. ) . $select_items[$lines_count]['answer'],
  895. [
  896. 'id' => "window_{$windowId}_answer",
  897. 'style' => 'display: none;'
  898. ]
  899. );
  900. } else {
  901. $s .= '&nbsp;';
  902. }
  903. $lines_count++;
  904. if (($lines_count - 1) == $num_suggestions) {
  905. while (isset($select_items[$lines_count])) {
  906. $s .= Display::tag('b', $select_items[$lines_count]['letter']);
  907. $s .= $select_items[$lines_count]['answer'];
  908. $lines_count++;
  909. }
  910. }
  911. $matching_correct_answer++;
  912. $s .= '</li>';
  913. }
  914. }
  915. } // end for()
  916. if ($show_comment) {
  917. $s .= '</table>';
  918. } else {
  919. if ($answerType == MATCHING || $answerType == UNIQUE_ANSWER_NO_OPTION || $answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  920. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  921. ) {
  922. $s .= '</table>';
  923. }
  924. }
  925. if ($answerType == DRAGGABLE) {
  926. $s .= "</ul></div>";
  927. $counterAnswer = 1;
  928. $s .= '<div class="col-xs-12"><div class="row">';
  929. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  930. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  931. $windowId = $questionId . '_' . $counterAnswer;
  932. if ($answerCorrect) {
  933. $s .= Display::div(
  934. $counterAnswer,
  935. [
  936. 'id' => "drop_$windowId",
  937. 'class' => 'droppable col-sm-4 well'
  938. ]
  939. );
  940. $counterAnswer++;
  941. }
  942. }
  943. $s .= '</div></div>';
  944. }
  945. if ($answerType == MATCHING) {
  946. $s .= '</div>';
  947. }
  948. $s .= '</div>';
  949. // destruction of the Answer object
  950. unset($objAnswerTmp);
  951. // destruction of the Question object
  952. unset($objQuestionTmp);
  953. if ($origin != 'export') {
  954. echo $s;
  955. } else {
  956. return $s;
  957. }
  958. } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  959. // Question is a HOT_SPOT
  960. //checking document/images visibility
  961. if (api_is_platform_admin() || api_is_course_admin()) {
  962. $course = api_get_course_info();
  963. $doc_id = DocumentManager::get_document_id(
  964. $course,
  965. '/images/' . $pictureName
  966. );
  967. if (is_numeric($doc_id)) {
  968. $images_folder_visibility = api_get_item_visibility(
  969. $course,
  970. 'document',
  971. $doc_id,
  972. api_get_session_id()
  973. );
  974. if (!$images_folder_visibility) {
  975. //This message is shown only to the course/platform admin if the image is set to visibility = false
  976. Display::display_warning_message(
  977. get_lang('ChangeTheVisibilityOfTheCurrentImage')
  978. );
  979. }
  980. }
  981. }
  982. $questionName = $objQuestionTmp->selectTitle();
  983. $questionDescription = $objQuestionTmp->selectDescription();
  984. if ($freeze) {
  985. echo Display::img($objQuestionTmp->selectPicturePath());
  986. return;
  987. }
  988. // Get the answers, make a list
  989. $objAnswerTmp = new Answer($questionId);
  990. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  991. // get answers of hotpost
  992. $answers_hotspot = array();
  993. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  994. $answers = $objAnswerTmp->selectAnswerByAutoId(
  995. $objAnswerTmp->selectAutoId($answerId)
  996. );
  997. $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer(
  998. $answerId
  999. );
  1000. }
  1001. // display answers of hotpost order by id
  1002. $answer_list = '<div style="padding: 10px; margin-left: 0px; border: 1px solid #A4A4A4; height: 408px; width: 200px;"><b>' . get_lang(
  1003. 'HotspotZones'
  1004. ) . '</b><dl>';
  1005. if (!empty($answers_hotspot)) {
  1006. ksort($answers_hotspot);
  1007. foreach ($answers_hotspot as $key => $value) {
  1008. $answer_list .= '<dt>' . $key . '.- ' . $value . '</dt><br />';
  1009. }
  1010. }
  1011. $answer_list .= '</dl></div>';
  1012. if ($answerType == HOT_SPOT_DELINEATION) {
  1013. $answer_list = '';
  1014. $swf_file = 'hotspot_delineation_user';
  1015. $swf_height = 405;
  1016. } else {
  1017. $swf_file = 'hotspot_user';
  1018. $swf_height = 436;
  1019. }
  1020. if (!$only_questions) {
  1021. if ($show_title) {
  1022. TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
  1023. echo '<div class="question_title">' . $current_item . '. ' . $questionName . '</div>';
  1024. }
  1025. //@todo I need to the get the feedback type
  1026. echo '<input type="hidden" name="hidden_hotspot_id" value="' . $questionId . '" />';
  1027. echo '<table class="exercise_questions" >
  1028. <tr>
  1029. <td valign="top" colspan="2">';
  1030. echo $questionDescription;
  1031. echo '</td></tr>';
  1032. }
  1033. $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
  1034. $s .= '<script type="text/javascript" src="../plugin/hotspot/JavaScriptFlashGateway.js"></script>
  1035. <script src="../plugin/hotspot/hotspot.js" type="text/javascript" ></script>
  1036. <script type="text/javascript">
  1037. <!--
  1038. // Globals
  1039. // Major version of Flash required
  1040. var requiredMajorVersion = 7;
  1041. // Minor version of Flash required
  1042. var requiredMinorVersion = 0;
  1043. // Minor version of Flash required
  1044. var requiredRevision = 0;
  1045. // the version of javascript supported
  1046. var jsVersion = 1.0;
  1047. // -->
  1048. </script>
  1049. <script language="VBScript" type="text/vbscript">
  1050. <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
  1051. Function VBGetSwfVer(i)
  1052. on error resume next
  1053. Dim swControl, swVersion
  1054. swVersion = 0
  1055. set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
  1056. if (IsObject(swControl)) then
  1057. swVersion = swControl.GetVariable("$version")
  1058. end if
  1059. VBGetSwfVer = swVersion
  1060. End Function
  1061. // -->
  1062. </script>
  1063. <script language="JavaScript1.1" type="text/javascript">
  1064. <!-- // Detect Client Browser type
  1065. var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
  1066. var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
  1067. var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
  1068. jsVersion = 1.1;
  1069. // JavaScript helper required to detect Flash Player PlugIn version information
  1070. function JSGetSwfVer(i) {
  1071. // NS/Opera version >= 3 check for Flash plugin in plugin array
  1072. if (navigator.plugins != null && navigator.plugins.length > 0) {
  1073. if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
  1074. var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
  1075. var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
  1076. descArray = flashDescription.split(" ");
  1077. tempArrayMajor = descArray[2].split(".");
  1078. versionMajor = tempArrayMajor[0];
  1079. versionMinor = tempArrayMajor[1];
  1080. if ( descArray[3] != "" ) {
  1081. tempArrayMinor = descArray[3].split("r");
  1082. } else {
  1083. tempArrayMinor = descArray[4].split("r");
  1084. }
  1085. versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
  1086. flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
  1087. } else {
  1088. flashVer = -1;
  1089. }
  1090. }
  1091. // MSN/WebTV 2.6 supports Flash 4
  1092. else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
  1093. // WebTV 2.5 supports Flash 3
  1094. else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
  1095. // older WebTV supports Flash 2
  1096. else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
  1097. // Can\'t detect in all other cases
  1098. else
  1099. {
  1100. flashVer = -1;
  1101. }
  1102. return flashVer;
  1103. }
  1104. // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
  1105. function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
  1106. reqVer = parseFloat(reqMajorVer + "." + reqRevision);
  1107. // loop backwards through the versions until we find the newest version
  1108. for (i=25;i>0;i--) {
  1109. if (isIE && isWin && !isOpera) {
  1110. versionStr = VBGetSwfVer(i);
  1111. } else {
  1112. versionStr = JSGetSwfVer(i);
  1113. }
  1114. if (versionStr == -1 ) {
  1115. return false;
  1116. } else if (versionStr != 0) {
  1117. if(isIE && isWin && !isOpera) {
  1118. tempArray = versionStr.split(" ");
  1119. tempString = tempArray[1];
  1120. versionArray = tempString .split(",");
  1121. } else {
  1122. versionArray = versionStr.split(".");
  1123. }
  1124. versionMajor = versionArray[0];
  1125. versionMinor = versionArray[1];
  1126. versionRevision = versionArray[2];
  1127. versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24
  1128. versionNum = parseFloat(versionString);
  1129. // is the major.revision >= requested major.revision AND the minor version >= requested minor
  1130. if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
  1131. return true;
  1132. } else {
  1133. return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
  1134. }
  1135. }
  1136. }
  1137. }
  1138. // -->
  1139. </script>';
  1140. $s .= '<tr><td valign="top" colspan="2" width="520"><table><tr><td width="520">
  1141. <script>
  1142. <!--
  1143. // Version check based upon the values entered above in "Globals"
  1144. var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
  1145. // Check to see if the version meets the requirements for playback
  1146. if (hasReqestedVersion) { // if we\'ve detected an acceptable version
  1147. var oeTags = \'<object type="application/x-shockwave-flash" data="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&amp;canClick:' . $canClick . '" width="600" height="' . $swf_height . '">\'
  1148. + \'<param name="wmode" value="transparent">\'
  1149. + \'<param name="movie" value="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&amp;canClick:' . $canClick . '" />\'
  1150. + \'<\/object>\';
  1151. document.write(oeTags); // embed the Flash Content SWF when all tests are passed
  1152. } else { // flash is too old or we can\'t detect the plugin
  1153. var alternateContent = "Error<br \/>"
  1154. + "Hotspots requires Macromedia Flash 7.<br \/>"
  1155. + "<a href=\"http://www.macromedia.com/go/getflash/\">Get Flash<\/a>";
  1156. document.write(alternateContent); // insert non-flash content
  1157. }
  1158. // -->
  1159. </script>
  1160. </td>
  1161. <td valign="top" align="left">' . $answer_list . '</td></tr>
  1162. </table>
  1163. </td></tr>';
  1164. echo $s;
  1165. echo '</table>';
  1166. }
  1167. return $nbrAnswers;
  1168. }
  1169. /**
  1170. * @param int $exe_id
  1171. * @return array
  1172. */
  1173. public static function get_exercise_track_exercise_info($exe_id)
  1174. {
  1175. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1176. $TBL_TRACK_EXERCICES = Database::get_main_table(
  1177. TABLE_STATISTIC_TRACK_E_EXERCISES
  1178. );
  1179. $TBL_COURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  1180. $exe_id = intval($exe_id);
  1181. $result = array();
  1182. if (!empty($exe_id)) {
  1183. $sql = " SELECT q.*, tee.*
  1184. FROM $TBL_EXERCICES as q
  1185. INNER JOIN $TBL_TRACK_EXERCICES as tee
  1186. ON q.id = tee.exe_exo_id
  1187. INNER JOIN $TBL_COURSE c
  1188. ON c.id = tee.c_id
  1189. WHERE tee.exe_id = $exe_id
  1190. AND q.c_id = c.id";
  1191. $res_fb_type = Database::query($sql);
  1192. $result = Database::fetch_array($res_fb_type, 'ASSOC');
  1193. }
  1194. return $result;
  1195. }
  1196. /**
  1197. * Validates the time control key
  1198. */
  1199. public static function exercise_time_control_is_valid(
  1200. $exercise_id,
  1201. $lp_id = 0,
  1202. $lp_item_id = 0
  1203. ) {
  1204. $course_id = api_get_course_int_id();
  1205. $exercise_id = intval($exercise_id);
  1206. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1207. $sql = "SELECT expired_time FROM $TBL_EXERCICES
  1208. WHERE c_id = $course_id AND id = $exercise_id";
  1209. $result = Database::query($sql);
  1210. $row = Database::fetch_array($result, 'ASSOC');
  1211. if (!empty($row['expired_time'])) {
  1212. $current_expired_time_key = ExerciseLib::get_time_control_key(
  1213. $exercise_id,
  1214. $lp_id,
  1215. $lp_item_id
  1216. );
  1217. if (isset($_SESSION['expired_time'][$current_expired_time_key])) {
  1218. $current_time = time();
  1219. $expired_time = api_strtotime(
  1220. $_SESSION['expired_time'][$current_expired_time_key],
  1221. 'UTC'
  1222. );
  1223. $total_time_allowed = $expired_time + 30;
  1224. if ($total_time_allowed < $current_time) {
  1225. return false;
  1226. }
  1227. return true;
  1228. } else {
  1229. return false;
  1230. }
  1231. } else {
  1232. return true;
  1233. }
  1234. }
  1235. /**
  1236. * Deletes the time control token
  1237. */
  1238. public static function exercise_time_control_delete(
  1239. $exercise_id,
  1240. $lp_id = 0,
  1241. $lp_item_id = 0
  1242. ) {
  1243. $current_expired_time_key = self::get_time_control_key(
  1244. $exercise_id,
  1245. $lp_id,
  1246. $lp_item_id
  1247. );
  1248. unset($_SESSION['expired_time'][$current_expired_time_key]);
  1249. }
  1250. /**
  1251. * Generates the time control key
  1252. */
  1253. public static function get_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0)
  1254. {
  1255. $exercise_id = intval($exercise_id);
  1256. $lp_id = intval($lp_id);
  1257. $lp_item_id = intval($lp_item_id);
  1258. return
  1259. api_get_course_int_id() . '_' .
  1260. api_get_session_id() . '_' .
  1261. $exercise_id . '_' .
  1262. api_get_user_id() . '_' .
  1263. $lp_id . '_' .
  1264. $lp_item_id;
  1265. }
  1266. /**
  1267. * Get session time control
  1268. */
  1269. public static function get_session_time_control_key(
  1270. $exercise_id,
  1271. $lp_id = 0,
  1272. $lp_item_id = 0
  1273. ) {
  1274. $return_value = 0;
  1275. $time_control_key = self::get_time_control_key(
  1276. $exercise_id,
  1277. $lp_id,
  1278. $lp_item_id
  1279. );
  1280. if (isset($_SESSION['expired_time']) && isset($_SESSION['expired_time'][$time_control_key])) {
  1281. $return_value = $_SESSION['expired_time'][$time_control_key];
  1282. }
  1283. return $return_value;
  1284. }
  1285. /**
  1286. * Gets count of exam results
  1287. * @todo this function should be moved in a library + no global calls
  1288. */
  1289. public static function get_count_exam_results($exercise_id, $extra_where_conditions)
  1290. {
  1291. $count = self::get_exam_results_data(
  1292. null,
  1293. null,
  1294. null,
  1295. null,
  1296. $exercise_id,
  1297. $extra_where_conditions,
  1298. true
  1299. );
  1300. return $count;
  1301. }
  1302. /**
  1303. * @param string $in_hotpot_path
  1304. * @return int
  1305. */
  1306. public static function get_count_exam_hotpotatoes_results($in_hotpot_path)
  1307. {
  1308. return self::get_exam_results_hotpotatoes_data(
  1309. 0,
  1310. 0,
  1311. '',
  1312. '',
  1313. $in_hotpot_path,
  1314. true,
  1315. ''
  1316. );
  1317. }
  1318. /**
  1319. * @param int $in_from
  1320. * @param int $in_number_of_items
  1321. * @param int $in_column
  1322. * @param int $in_direction
  1323. * @param string $in_hotpot_path
  1324. * @param bool $in_get_count
  1325. * @param null $where_condition
  1326. * @return array|int
  1327. */
  1328. public static function get_exam_results_hotpotatoes_data(
  1329. $in_from,
  1330. $in_number_of_items,
  1331. $in_column,
  1332. $in_direction,
  1333. $in_hotpot_path,
  1334. $in_get_count = false,
  1335. $where_condition = null
  1336. ) {
  1337. $courseId = api_get_course_int_id();
  1338. /* by default in_column = 1 If parameters given,
  1339. it is the name of the column witch is the bdd field name*/
  1340. if ($in_column == 1) {
  1341. $in_column = 'firstname';
  1342. }
  1343. $in_hotpot_path = Database::escape_string($in_hotpot_path);
  1344. $in_direction = Database::escape_string($in_direction);
  1345. $in_column = Database::escape_string($in_column);
  1346. $in_number_of_items = intval($in_number_of_items);
  1347. $in_from = intval($in_from);
  1348. $TBL_TRACK_HOTPOTATOES = Database:: get_main_table(
  1349. TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  1350. );
  1351. $TBL_USER = Database:: get_main_table(TABLE_MAIN_USER);
  1352. $sql = "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp
  1353. JOIN $TBL_USER u ON thp.exe_user_id = u.user_id
  1354. WHERE thp.c_id = $courseId AND exe_name LIKE '$in_hotpot_path%'";
  1355. // just count how many answers
  1356. if ($in_get_count) {
  1357. $res = Database::query($sql);
  1358. return Database::num_rows($res);
  1359. }
  1360. // get a number of sorted results
  1361. $sql .= " $where_condition
  1362. ORDER BY $in_column $in_direction
  1363. LIMIT $in_from, $in_number_of_items";
  1364. $res = Database::query($sql);
  1365. $result = array();
  1366. $apiIsAllowedToEdit = api_is_allowed_to_edit();
  1367. $urlBase = api_get_path(WEB_CODE_PATH) .
  1368. 'exercice/hotpotatoes_exercise_report.php?action=delete&' .
  1369. api_get_cidreq() . '&id=';
  1370. while ($data = Database::fetch_array($res)) {
  1371. $actions = null;
  1372. if ($apiIsAllowedToEdit) {
  1373. $url = $urlBase . $data['id'] . '&path=' . $data['exe_name'];
  1374. $actions = Display::url(
  1375. Display::return_icon('delete.png', get_lang('Delete')),
  1376. $url
  1377. );
  1378. }
  1379. $result[] = array(
  1380. 'firstname' => $data['firstname'],
  1381. 'lastname' => $data['lastname'],
  1382. 'username' => $data['username'],
  1383. 'group_name' => implode(
  1384. "<br/>",
  1385. GroupManager::get_user_group_name($data['user_id'])
  1386. ),
  1387. 'exe_date' => $data['exe_date'],
  1388. 'score' => $data['exe_result'] . ' / ' . $data['exe_weighting'],
  1389. 'actions' => $actions,
  1390. );
  1391. }
  1392. return $result;
  1393. }
  1394. /**
  1395. * @param string $exercisePath
  1396. * @param int $userId
  1397. * @param int $courseId
  1398. * @param int $sessionId
  1399. *
  1400. * @return array
  1401. */
  1402. public static function getLatestHotPotatoResult(
  1403. $exercisePath,
  1404. $userId,
  1405. $courseId,
  1406. $sessionId
  1407. ) {
  1408. $table = Database:: get_main_table(
  1409. TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  1410. );
  1411. $courseInfo = api_get_course_info_by_id($courseId);
  1412. $exercisePath = Database::escape_string($exercisePath);
  1413. $userId = intval($userId);
  1414. $sql = "SELECT * FROM $table
  1415. WHERE
  1416. c_id = $courseId AND
  1417. exe_name LIKE '$exercisePath%' AND
  1418. exe_user_id = $userId
  1419. ORDER BY id
  1420. LIMIT 1";
  1421. $result = Database::query($sql);
  1422. $attempt = array();
  1423. if (Database::num_rows($result)) {
  1424. $attempt = Database::fetch_array($result, 'ASSOC');
  1425. }
  1426. return $attempt;
  1427. }
  1428. /**
  1429. * Gets the exam'data results
  1430. * @todo this function should be moved in a library + no global calls
  1431. * @param int $from
  1432. * @param int $number_of_items
  1433. * @param int $column
  1434. * @param string $direction
  1435. * @param int $exercise_id
  1436. * @param null $extra_where_conditions
  1437. * @param bool $get_count
  1438. * @return array
  1439. */
  1440. public static function get_exam_results_data(
  1441. $from,
  1442. $number_of_items,
  1443. $column,
  1444. $direction,
  1445. $exercise_id,
  1446. $extra_where_conditions = null,
  1447. $get_count = false
  1448. ) {
  1449. //@todo replace all this globals
  1450. global $documentPath, $filter;
  1451. $course_id = api_get_course_int_id();
  1452. $course_code = api_get_course_id();
  1453. $sessionId = api_get_session_id();
  1454. $is_allowedToEdit = api_is_allowed_to_edit(
  1455. null,
  1456. true
  1457. ) || api_is_allowed_to_edit(true) || api_is_drh(
  1458. ) || api_is_student_boss();
  1459. $TBL_USER = Database:: get_main_table(TABLE_MAIN_USER);
  1460. $TBL_EXERCICES = Database:: get_course_table(TABLE_QUIZ_TEST);
  1461. $TBL_GROUP_REL_USER = Database:: get_course_table(TABLE_GROUP_USER);
  1462. $TBL_GROUP = Database:: get_course_table(TABLE_GROUP);
  1463. $TBL_TRACK_EXERCICES = Database:: get_main_table(
  1464. TABLE_STATISTIC_TRACK_E_EXERCISES
  1465. );
  1466. $TBL_TRACK_HOTPOTATOES = Database:: get_main_table(
  1467. TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  1468. );
  1469. $TBL_TRACK_ATTEMPT_RECORDING = Database:: get_main_table(
  1470. TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING
  1471. );
  1472. $session_id_and = ' AND te.session_id = ' . $sessionId . ' ';
  1473. $exercise_id = intval($exercise_id);
  1474. $exercise_where = '';
  1475. if (!empty($exercise_id)) {
  1476. $exercise_where .= ' AND te.exe_exo_id = ' . $exercise_id . ' ';
  1477. }
  1478. $hotpotatoe_where = '';
  1479. if (!empty($_GET['path'])) {
  1480. $hotpotatoe_path = Database::escape_string($_GET['path']);
  1481. $hotpotatoe_where .= ' AND exe_name = "' . $hotpotatoe_path . '" ';
  1482. }
  1483. // sql for chamilo-type tests for teacher / tutor view
  1484. $sql_inner_join_tbl_track_exercices = " (
  1485. SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised
  1486. FROM $TBL_TRACK_EXERCICES ttte LEFT JOIN $TBL_TRACK_ATTEMPT_RECORDING tr
  1487. ON (ttte.exe_id = tr.exe_id)
  1488. WHERE
  1489. c_id = $course_id AND
  1490. exe_exo_id = $exercise_id AND
  1491. ttte.session_id = " . $sessionId . "
  1492. )";
  1493. if ($is_allowedToEdit) {
  1494. //Teacher view
  1495. if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
  1496. //$exercise_where_query = ' te.exe_exo_id = ce.id AND ';
  1497. }
  1498. $sqlFromOption = "";
  1499. $sqlWhereOption = ""; // for hpsql
  1500. //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries
  1501. //Hack in order to filter groups
  1502. $sql_inner_join_tbl_user = '';
  1503. if (strpos($extra_where_conditions, 'group_id')) {
  1504. $sql_inner_join_tbl_user = "
  1505. (
  1506. SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
  1507. FROM $TBL_USER u
  1508. INNER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=" . $course_id . ")
  1509. INNER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id=" . $course_id . ")
  1510. )";
  1511. }
  1512. if (strpos($extra_where_conditions, 'group_all')) {
  1513. $extra_where_conditions = str_replace(
  1514. "AND ( group_id = 'group_all' )",
  1515. '',
  1516. $extra_where_conditions
  1517. );
  1518. $extra_where_conditions = str_replace(
  1519. "AND group_id = 'group_all'",
  1520. '',
  1521. $extra_where_conditions
  1522. );
  1523. $extra_where_conditions = str_replace(
  1524. "group_id = 'group_all' AND",
  1525. '',
  1526. $extra_where_conditions
  1527. );
  1528. $sql_inner_join_tbl_user = "
  1529. (
  1530. SELECT u.user_id, firstname, lastname, email, username, '' as group_name, '' as group_id
  1531. FROM $TBL_USER u
  1532. )";
  1533. $sql_inner_join_tbl_user = null;
  1534. }
  1535. if (strpos($extra_where_conditions, 'group_none')) {
  1536. $extra_where_conditions = str_replace(
  1537. "AND ( group_id = 'group_none' )",
  1538. "AND ( group_id is null )",
  1539. $extra_where_conditions
  1540. );
  1541. $extra_where_conditions = str_replace(
  1542. "AND group_id = 'group_none'",
  1543. "AND ( group_id is null )",
  1544. $extra_where_conditions
  1545. );
  1546. $sql_inner_join_tbl_user = "
  1547. (
  1548. SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
  1549. FROM $TBL_USER u
  1550. LEFT OUTER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=" . $course_id . " )
  1551. LEFT OUTER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id = " . $course_id . ")
  1552. )";
  1553. }
  1554. // All
  1555. $is_empty_sql_inner_join_tbl_user = false;
  1556. if (empty($sql_inner_join_tbl_user)) {
  1557. $is_empty_sql_inner_join_tbl_user = true;
  1558. $sql_inner_join_tbl_user = "
  1559. (
  1560. SELECT u.user_id, firstname, lastname, email, username, ' ' as group_name, '' as group_id, official_code
  1561. FROM $TBL_USER u
  1562. WHERE u.status NOT IN(" . api_get_users_status_ignored_in_reports(
  1563. 'string'
  1564. ) . ")
  1565. )";
  1566. }
  1567. $sqlFromOption = " , $TBL_GROUP_REL_USER AS gru ";
  1568. $sqlWhereOption = " AND gru.c_id = " . $course_id .
  1569. " AND gru.user_id = user.user_id ";
  1570. $first_and_last_name = api_is_western_name_order(
  1571. ) ? "firstname, lastname" : "lastname, firstname";
  1572. if ($get_count) {
  1573. $sql_select = "SELECT count(te.exe_id) ";
  1574. } else {
  1575. $sql_select = "SELECT DISTINCT
  1576. user_id,
  1577. $first_and_last_name,
  1578. official_code,
  1579. ce.title,
  1580. username,
  1581. te.exe_result,
  1582. te.exe_weighting,
  1583. te.exe_date,
  1584. te.exe_id,
  1585. email as exemail,
  1586. te.start_date,
  1587. steps_counter,
  1588. exe_user_id,
  1589. te.exe_duration,
  1590. propagate_neg,
  1591. revised,
  1592. group_name,
  1593. group_id,
  1594. orig_lp_id,
  1595. te.user_ip";
  1596. }
  1597. $sql = " $sql_select
  1598. FROM $TBL_EXERCICES AS ce
  1599. INNER JOIN $sql_inner_join_tbl_track_exercices AS te ON (te.exe_exo_id = ce.id)
  1600. INNER JOIN $sql_inner_join_tbl_user AS user ON (user.user_id = exe_user_id)
  1601. WHERE
  1602. te.status != 'incomplete' AND
  1603. te.c_id = " . $course_id . " $session_id_and AND
  1604. ce.active <>-1 AND ce.c_id = " . $course_id . "
  1605. $exercise_where
  1606. $extra_where_conditions
  1607. ";
  1608. // sql for hotpotatoes tests for teacher / tutor view
  1609. if ($get_count) {
  1610. $hpsql_select = "SELECT count(username)";
  1611. } else {
  1612. $hpsql_select = "SELECT
  1613. $first_and_last_name ,
  1614. username,
  1615. official_code,
  1616. tth.exe_name,
  1617. tth.exe_result ,
  1618. tth.exe_weighting,
  1619. tth.exe_date";
  1620. }
  1621. $hpsql = " $hpsql_select
  1622. FROM
  1623. $TBL_TRACK_HOTPOTATOES tth,
  1624. $TBL_USER user
  1625. $sqlFromOption
  1626. WHERE
  1627. user.user_id=tth.exe_user_id
  1628. AND tth.c_id = " . $course_id . "
  1629. $hotpotatoe_where
  1630. $sqlWhereOption
  1631. AND user.status NOT IN(" . api_get_users_status_ignored_in_reports(
  1632. 'string'
  1633. ) . ")
  1634. ORDER BY
  1635. tth.c_id ASC,
  1636. tth.exe_date DESC";
  1637. }
  1638. if ($get_count) {
  1639. $resx = Database::query($sql);
  1640. $rowx = Database::fetch_row($resx, 'ASSOC');
  1641. return $rowx[0];
  1642. }
  1643. $teacher_list = CourseManager::get_teacher_list_from_course_code(
  1644. api_get_course_id()
  1645. );
  1646. $teacher_id_list = array();
  1647. foreach ($teacher_list as $teacher) {
  1648. $teacher_id_list[] = $teacher['user_id'];
  1649. }
  1650. $list_info = array();
  1651. // Simple exercises
  1652. if (empty($hotpotatoe_where)) {
  1653. $column = !empty($column) ? Database::escape_string($column) : null;
  1654. $from = intval($from);
  1655. $number_of_items = intval($number_of_items);
  1656. if (!empty($column)) {
  1657. $sql .= " ORDER BY $column $direction ";
  1658. }
  1659. $sql .= " LIMIT $from, $number_of_items";
  1660. $results = array();
  1661. $resx = Database::query($sql);
  1662. while ($rowx = Database::fetch_array($resx, 'ASSOC')) {
  1663. $results[] = $rowx;
  1664. }
  1665. $group_list = GroupManager::get_group_list();
  1666. $clean_group_list = array();
  1667. if (!empty($group_list)) {
  1668. foreach ($group_list as $group) {
  1669. $clean_group_list[$group['id']] = $group['name'];
  1670. }
  1671. }
  1672. $lp_list_obj = new LearnpathList(api_get_user_id());
  1673. $lp_list = $lp_list_obj->get_flat_list();
  1674. if (is_array($results)) {
  1675. $users_array_id = array();
  1676. $from_gradebook = false;
  1677. if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
  1678. $from_gradebook = true;
  1679. }
  1680. $sizeof = count($results);
  1681. $user_list_id = array();
  1682. $locked = api_resource_is_locked_by_gradebook(
  1683. $exercise_id,
  1684. LINK_EXERCISE
  1685. );
  1686. // Looping results
  1687. for ($i = 0; $i < $sizeof; $i++) {
  1688. $revised = $results[$i]['revised'];
  1689. if ($from_gradebook && ($is_allowedToEdit)) {
  1690. if (in_array(
  1691. $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'],
  1692. $users_array_id
  1693. )) {
  1694. continue;
  1695. }
  1696. $users_array_id[] = $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'];
  1697. }
  1698. $lp_obj = isset($results[$i]['orig_lp_id']) && isset($lp_list[$results[$i]['orig_lp_id']]) ? $lp_list[$results[$i]['orig_lp_id']] : null;
  1699. $lp_name = null;
  1700. if ($lp_obj) {
  1701. $url = api_get_path(
  1702. WEB_CODE_PATH
  1703. ) . 'newscorm/lp_controller.php?' . api_get_cidreq(
  1704. ) . '&action=view&lp_id=' . $results[$i]['orig_lp_id'];
  1705. $lp_name = Display::url(
  1706. $lp_obj['lp_name'],
  1707. $url,
  1708. array('target' => '_blank')
  1709. );
  1710. }
  1711. //Add all groups by user
  1712. $group_name_list = null;
  1713. if ($is_empty_sql_inner_join_tbl_user) {
  1714. $group_list = GroupManager::get_group_ids(
  1715. api_get_course_int_id(),
  1716. $results[$i]['user_id']
  1717. );
  1718. foreach ($group_list as $id) {
  1719. $group_name_list .= $clean_group_list[$id] . '<br/>';
  1720. }
  1721. $results[$i]['group_name'] = $group_name_list;
  1722. }
  1723. $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round(
  1724. $results[$i]['exe_duration'] / 60
  1725. ) : 0;
  1726. $user_list_id[] = $results[$i]['exe_user_id'];
  1727. $id = $results[$i]['exe_id'];
  1728. $dt = api_convert_and_format_date(
  1729. $results[$i]['exe_weighting']
  1730. );
  1731. // we filter the results if we have the permission to
  1732. if (isset($results[$i]['results_disabled'])) {
  1733. $result_disabled = intval(
  1734. $results[$i]['results_disabled']
  1735. );
  1736. } else {
  1737. $result_disabled = 0;
  1738. }
  1739. if ($result_disabled == 0) {
  1740. $my_res = $results[$i]['exe_result'];
  1741. $my_total = $results[$i]['exe_weighting'];
  1742. $results[$i]['start_date'] = api_get_local_time(
  1743. $results[$i]['start_date']
  1744. );
  1745. $results[$i]['exe_date'] = api_get_local_time(
  1746. $results[$i]['exe_date']
  1747. );
  1748. if (!$results[$i]['propagate_neg'] && $my_res < 0) {
  1749. $my_res = 0;
  1750. }
  1751. $score = self::show_score($my_res, $my_total);
  1752. $actions = '';
  1753. if ($is_allowedToEdit) {
  1754. if (isset($teacher_id_list)) {
  1755. if (in_array(
  1756. $results[$i]['exe_user_id'],
  1757. $teacher_id_list
  1758. )) {
  1759. $actions .= Display::return_icon(
  1760. 'teachers.gif',
  1761. get_lang('Teacher')
  1762. );
  1763. }
  1764. }
  1765. if ($revised) {
  1766. $actions .= "<a href='exercise_show.php?" . api_get_cidreq(
  1767. ) . "&action=edit&id=$id'>" .
  1768. Display:: return_icon(
  1769. 'edit.png',
  1770. get_lang('Edit'),
  1771. array(),
  1772. ICON_SIZE_SMALL
  1773. );
  1774. $actions .= '&nbsp;';
  1775. } else {
  1776. $actions .= "<a href='exercise_show.php?" . api_get_cidreq(
  1777. ) . "&action=qualify&id=$id'>" .
  1778. Display:: return_icon(
  1779. 'quiz.gif',
  1780. get_lang('Qualify')
  1781. );
  1782. $actions .= '&nbsp;';
  1783. }
  1784. $actions .= "</a>";
  1785. if ($filter == 2) {
  1786. $actions .= ' <a href="exercise_history.php?' . api_get_cidreq(
  1787. ) . '&exe_id=' . $id . '">' .
  1788. Display:: return_icon(
  1789. 'history.gif',
  1790. get_lang('ViewHistoryChange')
  1791. ) . '</a>';
  1792. }
  1793. //Admin can always delete the attempt
  1794. if (($locked == false || api_is_platform_admin(
  1795. )) && !api_is_student_boss()
  1796. ) {
  1797. $ip = TrackingUserLog::get_ip_from_user_event(
  1798. $results[$i]['exe_user_id'],
  1799. date('Y-m-d h:i:s'),
  1800. false
  1801. );
  1802. $actions .= '<a href="http://www.whatsmyip.org/ip-geo-location/?ip=' . $ip . '" target="_blank"><img src="' . api_get_path(
  1803. WEB_CODE_PATH
  1804. ) . 'img/icons/22/info.png" title="' . $ip . '" /></a>';
  1805. $delete_link = '<a href="exercise_report.php?' . api_get_cidreq(
  1806. ) . '&filter_by_user=' . intval(
  1807. $_GET['filter_by_user']
  1808. ) . '&filter=' . $filter . '&exerciseId=' . $exercise_id . '&delete=delete&did=' . $id . '"
  1809. onclick="javascript:if(!confirm(\'' . sprintf(
  1810. get_lang('DeleteAttempt'),
  1811. $results[$i]['username'],
  1812. $dt
  1813. ) . '\')) return false;">' . Display:: return_icon(
  1814. 'delete.png',
  1815. get_lang('Delete')
  1816. ) . '</a>';
  1817. $delete_link = utf8_encode($delete_link);
  1818. if (api_is_drh() && !api_is_platform_admin()) {
  1819. $delete_link = null;
  1820. }
  1821. $actions .= $delete_link . '&nbsp;';
  1822. }
  1823. } else {
  1824. $attempt_url = api_get_path(
  1825. WEB_CODE_PATH
  1826. ) . 'exercice/result.php?' . api_get_cidreq(
  1827. ) . '&id=' . $results[$i]['exe_id'] . '&id_session=' . $sessionId . '&height=500&width=750';
  1828. $attempt_link = Display::url(
  1829. get_lang('Show'),
  1830. $attempt_url,
  1831. array('class' => 'ajax btn')
  1832. );
  1833. $actions .= $attempt_link;
  1834. }
  1835. if ($revised) {
  1836. $revised = Display::label(
  1837. get_lang('Validated'),
  1838. 'success'
  1839. );
  1840. } else {
  1841. $revised = Display::label(
  1842. get_lang('NotValidated'),
  1843. 'info'
  1844. );
  1845. }
  1846. if ($is_allowedToEdit) {
  1847. $results[$i]['status'] = $revised;
  1848. $results[$i]['score'] = $score;
  1849. $results[$i]['lp'] = $lp_name;
  1850. $results[$i]['actions'] = $actions;
  1851. $list_info[] = $results[$i];
  1852. } else {
  1853. $results[$i]['status'] = $revised;
  1854. $results[$i]['score'] = $score;
  1855. $results[$i]['actions'] = $actions;
  1856. $list_info[] = $results[$i];
  1857. }
  1858. }
  1859. }
  1860. }
  1861. } else {
  1862. $hpresults = StatsUtils::getManyResultsXCol($hpsql, 6);
  1863. // Print HotPotatoes test results.
  1864. if (is_array($hpresults)) {
  1865. for ($i = 0; $i < sizeof($hpresults); $i++) {
  1866. $hp_title = GetQuizName($hpresults[$i][3], $documentPath);
  1867. if ($hp_title == '') {
  1868. $hp_title = basename($hpresults[$i][3]);
  1869. }
  1870. $hp_date = api_get_local_time(
  1871. $hpresults[$i][6],
  1872. null,
  1873. date_default_timezone_get()
  1874. );
  1875. $hp_result = round(
  1876. ($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1)) * 100,
  1877. 2
  1878. ) . '% (' . $hpresults[$i][4] . ' / ' . $hpresults[$i][5] . ')';
  1879. if ($is_allowedToEdit) {
  1880. $list_info[] = array(
  1881. $hpresults[$i][0],
  1882. $hpresults[$i][1],
  1883. $hpresults[$i][2],
  1884. '',
  1885. $hp_title,
  1886. '-',
  1887. $hp_date,
  1888. $hp_result,
  1889. '-'
  1890. );
  1891. } else {
  1892. $list_info[] = array(
  1893. $hp_title,
  1894. '-',
  1895. $hp_date,
  1896. $hp_result,
  1897. '-'
  1898. );
  1899. }
  1900. }
  1901. }
  1902. }
  1903. return $list_info;
  1904. }
  1905. /**
  1906. * Converts the score with the exercise_max_note and exercise_min_score
  1907. * the platform settings + formats the results using the float_format function
  1908. *
  1909. * @param float $score
  1910. * @param float $weight
  1911. * @param bool $show_percentage show percentage or not
  1912. * @param bool $use_platform_settings use or not the platform settings
  1913. * @param bool $show_only_percentage
  1914. * @return string an html with the score modified
  1915. */
  1916. public static function show_score(
  1917. $score,
  1918. $weight,
  1919. $show_percentage = true,
  1920. $use_platform_settings = true,
  1921. $show_only_percentage = false
  1922. ) {
  1923. if (is_null($score) && is_null($weight)) {
  1924. return '-';
  1925. }
  1926. $max_note = api_get_setting('exercise_max_score');
  1927. $min_note = api_get_setting('exercise_min_score');
  1928. if ($use_platform_settings) {
  1929. if ($max_note != '' && $min_note != '') {
  1930. if (!empty($weight) && intval($weight) != 0) {
  1931. $score = $min_note + ($max_note - $min_note) * $score / $weight;
  1932. } else {
  1933. $score = $min_note;
  1934. }
  1935. $weight = $max_note;
  1936. }
  1937. }
  1938. $percentage = (100 * $score) / ($weight != 0 ? $weight : 1);
  1939. // Formats values
  1940. $percentage = float_format($percentage, 1);
  1941. $score = float_format($score, 1);
  1942. $weight = float_format($weight, 1);
  1943. $html = null;
  1944. if ($show_percentage) {
  1945. $parent = '(' . $score . ' / ' . $weight . ')';
  1946. $html = $percentage . "% $parent";
  1947. if ($show_only_percentage) {
  1948. $html = $percentage . "% ";
  1949. }
  1950. } else {
  1951. $html = $score . ' / ' . $weight;
  1952. }
  1953. $html = Display::span($html, array('class' => 'score_exercise'));
  1954. return $html;
  1955. }
  1956. /**
  1957. * @param float $score
  1958. * @param float $weight
  1959. * @param string $pass_percentage
  1960. * @return bool
  1961. */
  1962. public static function is_success_exercise_result($score, $weight, $pass_percentage)
  1963. {
  1964. $percentage = float_format(
  1965. ($score / ($weight != 0 ? $weight : 1)) * 100,
  1966. 1
  1967. );
  1968. if (isset($pass_percentage) && !empty($pass_percentage)) {
  1969. if ($percentage >= $pass_percentage) {
  1970. return true;
  1971. }
  1972. }
  1973. return false;
  1974. }
  1975. /**
  1976. * @param float $score
  1977. * @param float $weight
  1978. * @param string $pass_percentage
  1979. * @return string
  1980. */
  1981. public static function show_success_message($score, $weight, $pass_percentage)
  1982. {
  1983. $res = "";
  1984. if (self::is_pass_pourcentage_enabled($pass_percentage)) {
  1985. $is_success = self::is_success_exercise_result(
  1986. $score,
  1987. $weight,
  1988. $pass_percentage
  1989. );
  1990. if ($is_success) {
  1991. $html = get_lang('CongratulationsYouPassedTheTest');
  1992. $icon = Display::return_icon(
  1993. 'completed.png',
  1994. get_lang('Correct'),
  1995. array(),
  1996. ICON_SIZE_MEDIUM
  1997. );
  1998. } else {
  1999. //$html .= Display::return_message(get_lang('YouDidNotReachTheMinimumScore'), 'warning');
  2000. $html = get_lang('YouDidNotReachTheMinimumScore');
  2001. $icon = Display::return_icon(
  2002. 'warning.png',
  2003. get_lang('Wrong'),
  2004. array(),
  2005. ICON_SIZE_MEDIUM
  2006. );
  2007. }
  2008. $html = Display::tag('h4', $html);
  2009. $html .= Display::tag(
  2010. 'h5',
  2011. $icon,
  2012. array('style' => 'width:40px; padding:2px 10px 0px 0px')
  2013. );
  2014. $res = $html;
  2015. }
  2016. return $res;
  2017. }
  2018. /**
  2019. * Return true if pass_pourcentage activated (we use the pass pourcentage feature
  2020. * return false if pass_percentage = 0 (we don't use the pass pourcentage feature
  2021. * @param $in_pass_pourcentage
  2022. * @return boolean
  2023. * In this version, pass_percentage and show_success_message are disabled if
  2024. * pass_percentage is set to 0
  2025. */
  2026. public static function is_pass_pourcentage_enabled($in_pass_pourcentage)
  2027. {
  2028. return $in_pass_pourcentage > 0;
  2029. }
  2030. /**
  2031. * Converts a numeric value in a percentage example 0.66666 to 66.67 %
  2032. * @param $value
  2033. * @return float Converted number
  2034. */
  2035. public static function convert_to_percentage($value)
  2036. {
  2037. $return = '-';
  2038. if ($value != '') {
  2039. $return = float_format($value * 100, 1) . ' %';
  2040. }
  2041. return $return;
  2042. }
  2043. /**
  2044. * Converts a score/weight values to the platform scale
  2045. * @param float $score
  2046. * @param float $weight
  2047. * @deprecated seem not to be used
  2048. * @return float the score rounded converted to the new range
  2049. */
  2050. public static function convert_score($score, $weight)
  2051. {
  2052. $max_note = api_get_setting('exercise_max_score');
  2053. $min_note = api_get_setting('exercise_min_score');
  2054. if ($score != '' && $weight != '') {
  2055. if ($max_note != '' && $min_note != '') {
  2056. if (!empty($weight)) {
  2057. $score = $min_note + ($max_note - $min_note) * $score / $weight;
  2058. } else {
  2059. $score = $min_note;
  2060. }
  2061. }
  2062. }
  2063. $score_rounded = float_format($score, 1);
  2064. return $score_rounded;
  2065. }
  2066. /**
  2067. * Getting all active exercises from a course from a session
  2068. * (if a session_id is provided we will show all the exercises in the course +
  2069. * all exercises in the session)
  2070. * @param array $course_info
  2071. * @param int $session_id
  2072. * @param boolean $check_publication_dates
  2073. * @param string $search Search exercise name
  2074. * @param boolean $search_all_sessions Search exercises in all sessions
  2075. * @param int 0 = only inactive exercises
  2076. * 1 = only active exercises,
  2077. * 2 = all exercises
  2078. * 3 = active <> -1
  2079. * @return array array with exercise data
  2080. */
  2081. public static function get_all_exercises(
  2082. $course_info = null,
  2083. $session_id = 0,
  2084. $check_publication_dates = false,
  2085. $search = '',
  2086. $search_all_sessions = false,
  2087. $active = 2
  2088. ) {
  2089. $course_id = api_get_course_int_id();
  2090. if (!empty($course_info) && !empty($course_info['real_id'])) {
  2091. $course_id = $course_info['real_id'];
  2092. }
  2093. if ($session_id == -1) {
  2094. $session_id = 0;
  2095. }
  2096. $now = api_get_utc_datetime();
  2097. $time_conditions = '';
  2098. if ($check_publication_dates) {
  2099. //start and end are set
  2100. $time_conditions = " AND ((start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now' ) OR ";
  2101. // only start is set
  2102. $time_conditions .= " (start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time = '0000-00-00 00:00:00') OR ";
  2103. // only end is set
  2104. $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now') OR ";
  2105. // nothing is set
  2106. $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time = '0000-00-00 00:00:00')) ";
  2107. }
  2108. $needle_where = !empty($search) ? " AND title LIKE '?' " : '';
  2109. $needle = !empty($search) ? "%" . $search . "%" : '';
  2110. // Show courses by active status
  2111. $active_sql = '';
  2112. if ($active == 3) {
  2113. $active_sql = ' active <> -1 AND';
  2114. } else {
  2115. if ($active != 2) {
  2116. $active_sql = sprintf(' active = %d AND', $active);
  2117. }
  2118. }
  2119. if ($search_all_sessions == true) {
  2120. $conditions = array(
  2121. 'where' => array(
  2122. $active_sql . ' c_id = ? ' . $needle_where . $time_conditions => array(
  2123. $course_id,
  2124. $needle
  2125. )
  2126. ),
  2127. 'order' => 'title'
  2128. );
  2129. } else {
  2130. if ($session_id == 0) {
  2131. $conditions = array(
  2132. 'where' => array(
  2133. $active_sql . ' session_id = ? AND c_id = ? ' . $needle_where . $time_conditions => array(
  2134. $session_id,
  2135. $course_id,
  2136. $needle
  2137. )
  2138. ),
  2139. 'order' => 'title'
  2140. );
  2141. } else {
  2142. $conditions = array(
  2143. 'where' => array(
  2144. $active_sql . ' (session_id = 0 OR session_id = ? ) AND c_id = ? ' . $needle_where . $time_conditions => array(
  2145. $session_id,
  2146. $course_id,
  2147. $needle
  2148. )
  2149. ),
  2150. 'order' => 'title'
  2151. );
  2152. }
  2153. }
  2154. $table = Database:: get_course_table(TABLE_QUIZ_TEST);
  2155. return Database::select('*', $table, $conditions);
  2156. }
  2157. /**
  2158. * Get exercise information by id
  2159. * @param int $exerciseId Exercise Id
  2160. * @param int $courseId The course ID (necessary as c_quiz.id is not unique)
  2161. * @return array Exercise info
  2162. */
  2163. public static function get_exercise_by_id($exerciseId = 0, $courseId = null)
  2164. {
  2165. $TBL_EXERCICES = Database:: get_course_table(TABLE_QUIZ_TEST);
  2166. if (empty($courseId)) {
  2167. $courseId = api_get_course_int_id();
  2168. } else {
  2169. $courseId = intval($courseId);
  2170. }
  2171. $conditions = array(
  2172. 'where' => array(
  2173. 'id = ?' => array($exerciseId),
  2174. ' AND c_id = ? ' => $courseId
  2175. )
  2176. );
  2177. return Database::select('*', $TBL_EXERCICES, $conditions);
  2178. }
  2179. /**
  2180. * Getting all exercises (active only or all)
  2181. * from a course from a session
  2182. * (if a session_id is provided we will show all the exercises in the
  2183. * course + all exercises in the session)
  2184. * @param array course data
  2185. * @param int session id
  2186. * @param int course c_id
  2187. * @param boolean $only_active_exercises
  2188. * @return array array with exercise data
  2189. * modified by Hubert Borderiou
  2190. */
  2191. public static function get_all_exercises_for_course_id(
  2192. $course_info = null,
  2193. $session_id = 0,
  2194. $course_id = 0,
  2195. $only_active_exercises = true
  2196. ) {
  2197. $TBL_EXERCISES = Database:: get_course_table(TABLE_QUIZ_TEST);
  2198. if ($only_active_exercises) {
  2199. // Only active exercises.
  2200. $sql_active_exercises = "active = 1 AND ";
  2201. } else {
  2202. // Not only active means visible and invisible NOT deleted (-2)
  2203. $sql_active_exercises = "active IN (1, 0) AND ";
  2204. }
  2205. if ($session_id == -1) {
  2206. $session_id = 0;
  2207. }
  2208. $params = array(
  2209. $session_id,
  2210. $course_id
  2211. );
  2212. if ($session_id == 0) {
  2213. $conditions = array(
  2214. 'where' => array("$sql_active_exercises session_id = ? AND c_id = ?" => $params),
  2215. 'order' => 'title'
  2216. );
  2217. } else {
  2218. // All exercises
  2219. $conditions = array(
  2220. 'where' => array("$sql_active_exercises (session_id = 0 OR session_id = ? ) AND c_id=?" => $params),
  2221. 'order' => 'title'
  2222. );
  2223. }
  2224. return Database::select('*', $TBL_EXERCISES, $conditions);
  2225. }
  2226. /**
  2227. * Gets the position of the score based in a given score (result/weight)
  2228. * and the exe_id based in the user list
  2229. * (NO Exercises in LPs )
  2230. * @param float $my_score user score to be compared *attention*
  2231. * $my_score = score/weight and not just the score
  2232. * @param int $my_exe_id exe id of the exercise
  2233. * (this is necessary because if 2 students have the same score the one
  2234. * with the minor exe_id will have a best position, just to be fair and FIFO)
  2235. * @param int $exercise_id
  2236. * @param string $course_code
  2237. * @param int $session_id
  2238. * @param array $user_list
  2239. * @param bool $return_string
  2240. *
  2241. * @return int the position of the user between his friends in a course
  2242. * (or course within a session)
  2243. */
  2244. public static function get_exercise_result_ranking(
  2245. $my_score,
  2246. $my_exe_id,
  2247. $exercise_id,
  2248. $course_code,
  2249. $session_id = 0,
  2250. $user_list = array(),
  2251. $return_string = true
  2252. ) {
  2253. //No score given we return
  2254. if (is_null($my_score)) {
  2255. return '-';
  2256. }
  2257. if (empty($user_list)) {
  2258. return '-';
  2259. }
  2260. $best_attempts = array();
  2261. foreach ($user_list as $user_data) {
  2262. $user_id = $user_data['user_id'];
  2263. $best_attempts[$user_id] = self::get_best_attempt_by_user(
  2264. $user_id,
  2265. $exercise_id,
  2266. $course_code,
  2267. $session_id
  2268. );
  2269. }
  2270. if (empty($best_attempts)) {
  2271. return 1;
  2272. } else {
  2273. $position = 1;
  2274. $my_ranking = array();
  2275. foreach ($best_attempts as $user_id => $result) {
  2276. if (!empty($result['exe_weighting']) && intval(
  2277. $result['exe_weighting']
  2278. ) != 0
  2279. ) {
  2280. $my_ranking[$user_id] = $result['exe_result'] / $result['exe_weighting'];
  2281. } else {
  2282. $my_ranking[$user_id] = 0;
  2283. }
  2284. }
  2285. //if (!empty($my_ranking)) {
  2286. asort($my_ranking);
  2287. $position = count($my_ranking);
  2288. if (!empty($my_ranking)) {
  2289. foreach ($my_ranking as $user_id => $ranking) {
  2290. if ($my_score >= $ranking) {
  2291. if ($my_score == $ranking) {
  2292. $exe_id = $best_attempts[$user_id]['exe_id'];
  2293. if ($my_exe_id < $exe_id) {
  2294. $position--;
  2295. }
  2296. } else {
  2297. $position--;
  2298. }
  2299. }
  2300. }
  2301. }
  2302. //}
  2303. $return_value = array(
  2304. 'position' => $position,
  2305. 'count' => count($my_ranking)
  2306. );
  2307. if ($return_string) {
  2308. if (!empty($position) && !empty($my_ranking)) {
  2309. $return_value = $position . '/' . count($my_ranking);
  2310. } else {
  2311. $return_value = '-';
  2312. }
  2313. }
  2314. return $return_value;
  2315. }
  2316. }
  2317. /**
  2318. * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts
  2319. * (NO Exercises in LPs ) old functionality by attempt
  2320. * @param float user score to be compared attention => score/weight
  2321. * @param int exe id of the exercise
  2322. * (this is necessary because if 2 students have the same score the one
  2323. * with the minor exe_id will have a best position, just to be fair and FIFO)
  2324. * @param int exercise id
  2325. * @param string course code
  2326. * @param int session id
  2327. * @return int the position of the user between his friends in a course (or course within a session)
  2328. */
  2329. public static function get_exercise_result_ranking_by_attempt(
  2330. $my_score,
  2331. $my_exe_id,
  2332. $exercise_id,
  2333. $courseId,
  2334. $session_id = 0,
  2335. $return_string = true
  2336. ) {
  2337. if (empty($session_id)) {
  2338. $session_id = 0;
  2339. }
  2340. if (is_null($my_score)) {
  2341. return '-';
  2342. }
  2343. $user_results = Event::get_all_exercise_results(
  2344. $exercise_id,
  2345. $courseId,
  2346. $session_id,
  2347. false
  2348. );
  2349. $position_data = array();
  2350. if (empty($user_results)) {
  2351. return 1;
  2352. } else {
  2353. $position = 1;
  2354. $my_ranking = array();
  2355. foreach ($user_results as $result) {
  2356. //print_r($result);
  2357. if (!empty($result['exe_weighting']) && intval(
  2358. $result['exe_weighting']
  2359. ) != 0
  2360. ) {
  2361. $my_ranking[$result['exe_id']] = $result['exe_result'] / $result['exe_weighting'];
  2362. } else {
  2363. $my_ranking[$result['exe_id']] = 0;
  2364. }
  2365. }
  2366. asort($my_ranking);
  2367. $position = count($my_ranking);
  2368. if (!empty($my_ranking)) {
  2369. foreach ($my_ranking as $exe_id => $ranking) {
  2370. if ($my_score >= $ranking) {
  2371. if ($my_score == $ranking) {
  2372. if ($my_exe_id < $exe_id) {
  2373. $position--;
  2374. }
  2375. } else {
  2376. $position--;
  2377. }
  2378. }
  2379. }
  2380. }
  2381. $return_value = array(
  2382. 'position' => $position,
  2383. 'count' => count($my_ranking)
  2384. );
  2385. if ($return_string) {
  2386. if (!empty($position) && !empty($my_ranking)) {
  2387. return $position . '/' . count($my_ranking);
  2388. }
  2389. }
  2390. return $return_value;
  2391. }
  2392. }
  2393. /**
  2394. * Get the best attempt in a exercise (NO Exercises in LPs )
  2395. * @param int $exercise_id
  2396. * @param int $courseId
  2397. * @param int $session_id
  2398. *
  2399. * @return array
  2400. */
  2401. public static function get_best_attempt_in_course($exercise_id, $courseId, $session_id)
  2402. {
  2403. $user_results = Event::get_all_exercise_results(
  2404. $exercise_id,
  2405. $courseId,
  2406. $session_id,
  2407. false
  2408. );
  2409. $best_score_data = array();
  2410. $best_score = 0;
  2411. if (!empty($user_results)) {
  2412. foreach ($user_results as $result) {
  2413. if (!empty($result['exe_weighting']) && intval(
  2414. $result['exe_weighting']
  2415. ) != 0
  2416. ) {
  2417. $score = $result['exe_result'] / $result['exe_weighting'];
  2418. if ($score >= $best_score) {
  2419. $best_score = $score;
  2420. $best_score_data = $result;
  2421. }
  2422. }
  2423. }
  2424. }
  2425. return $best_score_data;
  2426. }
  2427. /**
  2428. * Get the best score in a exercise (NO Exercises in LPs )
  2429. * @param int $user_id
  2430. * @param int $exercise_id
  2431. * @param int $courseId
  2432. * @param int $session_id
  2433. *
  2434. * @return array
  2435. */
  2436. public static function get_best_attempt_by_user(
  2437. $user_id,
  2438. $exercise_id,
  2439. $courseId,
  2440. $session_id
  2441. ) {
  2442. $user_results = Event::get_all_exercise_results(
  2443. $exercise_id,
  2444. $courseId,
  2445. $session_id,
  2446. false,
  2447. $user_id
  2448. );
  2449. $best_score_data = array();
  2450. $best_score = 0;
  2451. if (!empty($user_results)) {
  2452. foreach ($user_results as $result) {
  2453. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2454. $score = $result['exe_result'] / $result['exe_weighting'];
  2455. if ($score >= $best_score) {
  2456. $best_score = $score;
  2457. $best_score_data = $result;
  2458. }
  2459. }
  2460. }
  2461. }
  2462. return $best_score_data;
  2463. }
  2464. /**
  2465. * Get average score (NO Exercises in LPs )
  2466. * @param int exercise id
  2467. * @param int $courseId
  2468. * @param int session id
  2469. * @return float Average score
  2470. */
  2471. public static function get_average_score($exercise_id, $courseId, $session_id)
  2472. {
  2473. $user_results = Event::get_all_exercise_results(
  2474. $exercise_id,
  2475. $courseId,
  2476. $session_id
  2477. );
  2478. $avg_score = 0;
  2479. if (!empty($user_results)) {
  2480. foreach ($user_results as $result) {
  2481. if (!empty($result['exe_weighting']) && intval(
  2482. $result['exe_weighting']
  2483. ) != 0
  2484. ) {
  2485. $score = $result['exe_result'] / $result['exe_weighting'];
  2486. $avg_score += $score;
  2487. }
  2488. }
  2489. $avg_score = float_format($avg_score / count($user_results), 1);
  2490. }
  2491. return $avg_score;
  2492. }
  2493. /**
  2494. * Get average score by score (NO Exercises in LPs )
  2495. * @param int exercise id
  2496. * @param int $courseId
  2497. * @param int session id
  2498. * @return float Average score
  2499. */
  2500. public static function get_average_score_by_course($courseId, $session_id)
  2501. {
  2502. $user_results = Event::get_all_exercise_results_by_course(
  2503. $courseId,
  2504. $session_id,
  2505. false
  2506. );
  2507. //echo $course_code.' - '.$session_id.'<br />';
  2508. $avg_score = 0;
  2509. if (!empty($user_results)) {
  2510. foreach ($user_results as $result) {
  2511. if (!empty($result['exe_weighting']) && intval(
  2512. $result['exe_weighting']
  2513. ) != 0
  2514. ) {
  2515. $score = $result['exe_result'] / $result['exe_weighting'];
  2516. $avg_score += $score;
  2517. }
  2518. }
  2519. //We asume that all exe_weighting
  2520. $avg_score = ($avg_score / count($user_results));
  2521. }
  2522. return $avg_score;
  2523. }
  2524. /**
  2525. * @param int $user_id
  2526. * @param int $courseId
  2527. * @param int $session_id
  2528. *
  2529. * @return float|int
  2530. */
  2531. public static function get_average_score_by_course_by_user(
  2532. $user_id,
  2533. $courseId,
  2534. $session_id
  2535. ) {
  2536. $user_results = Event::get_all_exercise_results_by_user(
  2537. $user_id,
  2538. $courseId,
  2539. $session_id
  2540. );
  2541. $avg_score = 0;
  2542. if (!empty($user_results)) {
  2543. foreach ($user_results as $result) {
  2544. if (!empty($result['exe_weighting']) && intval(
  2545. $result['exe_weighting']
  2546. ) != 0
  2547. ) {
  2548. $score = $result['exe_result'] / $result['exe_weighting'];
  2549. $avg_score += $score;
  2550. }
  2551. }
  2552. //We asume that all exe_weighting
  2553. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  2554. $avg_score = ($avg_score / count($user_results));
  2555. }
  2556. return $avg_score;
  2557. }
  2558. /**
  2559. * Get average score by score (NO Exercises in LPs )
  2560. * @param int exercise id
  2561. * @param int $courseId
  2562. * @param int session id
  2563. * @return float Best average score
  2564. */
  2565. public static function get_best_average_score_by_exercise(
  2566. $exercise_id,
  2567. $courseId,
  2568. $session_id,
  2569. $user_count
  2570. ) {
  2571. $user_results = Event::get_best_exercise_results_by_user(
  2572. $exercise_id,
  2573. $courseId,
  2574. $session_id
  2575. );
  2576. $avg_score = 0;
  2577. if (!empty($user_results)) {
  2578. foreach ($user_results as $result) {
  2579. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2580. $score = $result['exe_result'] / $result['exe_weighting'];
  2581. $avg_score += $score;
  2582. }
  2583. }
  2584. //We asume that all exe_weighting
  2585. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  2586. //$avg_score = ($avg_score / count($user_results));
  2587. if (!empty($user_count)) {
  2588. $avg_score = float_format($avg_score / $user_count, 1) * 100;
  2589. } else {
  2590. $avg_score = 0;
  2591. }
  2592. }
  2593. return $avg_score;
  2594. }
  2595. /**
  2596. * @param string $course_code
  2597. * @param int $session_id
  2598. *
  2599. * @return array
  2600. */
  2601. public static function get_exercises_to_be_taken($course_code, $session_id)
  2602. {
  2603. $course_info = api_get_course_info($course_code);
  2604. $exercises = self::get_all_exercises($course_info, $session_id);
  2605. $result = array();
  2606. $now = time() + 15 * 24 * 60 * 60;
  2607. foreach ($exercises as $exercise_item) {
  2608. if (isset($exercise_item['end_time']) &&
  2609. !empty($exercise_item['end_time']) &&
  2610. $exercise_item['end_time'] != '0000-00-00 00:00:00' &&
  2611. api_strtotime($exercise_item['end_time'], 'UTC') < $now
  2612. ) {
  2613. $result[] = $exercise_item;
  2614. }
  2615. }
  2616. return $result;
  2617. }
  2618. /**
  2619. * Get student results (only in completed exercises) stats by question
  2620. * @param int $question_id
  2621. * @param int $exercise_id
  2622. * @param string $course_code
  2623. * @param int $session_id
  2624. *
  2625. **/
  2626. public static function get_student_stats_by_question(
  2627. $question_id,
  2628. $exercise_id,
  2629. $course_code,
  2630. $session_id
  2631. ) {
  2632. $track_exercises = Database::get_main_table(
  2633. TABLE_STATISTIC_TRACK_E_EXERCISES
  2634. );
  2635. $track_attempt = Database::get_main_table(
  2636. TABLE_STATISTIC_TRACK_E_ATTEMPT
  2637. );
  2638. $question_id = intval($question_id);
  2639. $exercise_id = intval($exercise_id);
  2640. $course_code = Database::escape_string($course_code);
  2641. $session_id = intval($session_id);
  2642. $courseId = api_get_course_int_id($course_code);
  2643. $sql = "SELECT MAX(marks) as max, MIN(marks) as min, AVG(marks) as average
  2644. FROM $track_exercises e
  2645. INNER JOIN $track_attempt a
  2646. ON (
  2647. a.exe_id = e.exe_id AND
  2648. e.c_id = a.c_id AND
  2649. e.session_id = a.session_id
  2650. )
  2651. WHERE
  2652. exe_exo_id = $exercise_id AND
  2653. a.c_id = $courseId AND
  2654. e.session_id = $session_id AND
  2655. question_id = $question_id AND
  2656. status = ''
  2657. LIMIT 1";
  2658. $result = Database::query($sql);
  2659. $return = array();
  2660. if ($result) {
  2661. $return = Database::fetch_array($result, 'ASSOC');
  2662. }
  2663. return $return;
  2664. }
  2665. /**
  2666. * @param int $question_id
  2667. * @param int $exercise_id
  2668. * @param string $course_code
  2669. * @param int $session_id
  2670. * @return int
  2671. */
  2672. public static function get_number_students_question_with_answer_count(
  2673. $question_id,
  2674. $exercise_id,
  2675. $course_code,
  2676. $session_id
  2677. ) {
  2678. $track_exercises = Database::get_main_table(
  2679. TABLE_STATISTIC_TRACK_E_EXERCISES
  2680. );
  2681. $track_attempt = Database::get_main_table(
  2682. TABLE_STATISTIC_TRACK_E_ATTEMPT
  2683. );
  2684. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2685. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2686. $courseUserSession = Database::get_main_table(
  2687. TABLE_MAIN_SESSION_COURSE_USER
  2688. );
  2689. $question_id = intval($question_id);
  2690. $exercise_id = intval($exercise_id);
  2691. $courseId = api_get_course_int_id($course_code);
  2692. $session_id = intval($session_id);
  2693. if (empty($session_id)) {
  2694. $courseCondition = "
  2695. INNER JOIN $courseUser cu
  2696. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2697. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT;
  2698. } else {
  2699. $courseCondition = "
  2700. INNER JOIN $courseUserSession cu
  2701. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2702. $courseConditionWhere = " AND cu.status = 0 ";
  2703. }
  2704. $sql = "SELECT DISTINCT exe_user_id
  2705. FROM $track_exercises e
  2706. INNER JOIN $track_attempt a
  2707. ON (
  2708. a.exe_id = e.exe_id AND
  2709. e.c_id = a.c_id AND
  2710. e.session_id = a.session_id
  2711. )
  2712. INNER JOIN $courseTable c
  2713. ON (c.code = a.course_code)
  2714. $courseCondition
  2715. WHERE
  2716. exe_exo_id = $exercise_id AND
  2717. a.c_id = $courseId AND
  2718. e.session_id = $session_id AND
  2719. question_id = $question_id AND
  2720. answer <> '0' AND
  2721. e.status = ''
  2722. $courseConditionWhere
  2723. ";
  2724. $result = Database::query($sql);
  2725. $return = 0;
  2726. if ($result) {
  2727. $return = Database::num_rows($result);
  2728. }
  2729. return $return;
  2730. }
  2731. /**
  2732. * @param int $answer_id
  2733. * @param int $question_id
  2734. * @param int $exercise_id
  2735. * @param string $course_code
  2736. * @param int $session_id
  2737. *
  2738. * @return int
  2739. */
  2740. public static function get_number_students_answer_hotspot_count(
  2741. $answer_id,
  2742. $question_id,
  2743. $exercise_id,
  2744. $course_code,
  2745. $session_id
  2746. ) {
  2747. $track_exercises = Database::get_main_table(
  2748. TABLE_STATISTIC_TRACK_E_EXERCISES
  2749. );
  2750. $track_hotspot = Database::get_main_table(
  2751. TABLE_STATISTIC_TRACK_E_HOTSPOT
  2752. );
  2753. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2754. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2755. $courseUserSession = Database::get_main_table(
  2756. TABLE_MAIN_SESSION_COURSE_USER
  2757. );
  2758. $question_id = intval($question_id);
  2759. $answer_id = intval($answer_id);
  2760. $exercise_id = intval($exercise_id);
  2761. $course_code = Database::escape_string($course_code);
  2762. $session_id = intval($session_id);
  2763. if (empty($session_id)) {
  2764. $courseCondition = "
  2765. INNER JOIN $courseUser cu
  2766. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2767. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT;
  2768. } else {
  2769. $courseCondition = "
  2770. INNER JOIN $courseUserSession cu
  2771. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2772. $courseConditionWhere = " AND cu.status = 0 ";
  2773. }
  2774. $sql = "SELECT DISTINCT exe_user_id
  2775. FROM $track_exercises e
  2776. INNER JOIN $track_hotspot a
  2777. ON (a.hotspot_exe_id = e.exe_id)
  2778. INNER JOIN $courseTable c
  2779. ON (hotspot_course_code = c.code)
  2780. $courseCondition
  2781. WHERE
  2782. exe_exo_id = $exercise_id AND
  2783. a.hotspot_course_code = '$course_code' AND
  2784. e.session_id = $session_id AND
  2785. hotspot_answer_id = $answer_id AND
  2786. hotspot_question_id = $question_id AND
  2787. hotspot_correct = 1 AND
  2788. e.status = ''
  2789. $courseConditionWhere
  2790. ";
  2791. $result = Database::query($sql);
  2792. $return = 0;
  2793. if ($result) {
  2794. $return = Database::num_rows($result);
  2795. }
  2796. return $return;
  2797. }
  2798. /**
  2799. * @param int $answer_id
  2800. * @param int $question_id
  2801. * @param int $exercise_id
  2802. * @param string $course_code
  2803. * @param int $session_id
  2804. * @param string $question_type
  2805. * @param string $correct_answer
  2806. * @param string $current_answer
  2807. * @return int
  2808. */
  2809. public static function get_number_students_answer_count(
  2810. $answer_id,
  2811. $question_id,
  2812. $exercise_id,
  2813. $course_code,
  2814. $session_id,
  2815. $question_type = null,
  2816. $correct_answer = null,
  2817. $current_answer = null
  2818. ) {
  2819. $track_exercises = Database::get_main_table(
  2820. TABLE_STATISTIC_TRACK_E_EXERCISES
  2821. );
  2822. $track_attempt = Database::get_main_table(
  2823. TABLE_STATISTIC_TRACK_E_ATTEMPT
  2824. );
  2825. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2826. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2827. $courseUserSession = Database::get_main_table(
  2828. TABLE_MAIN_SESSION_COURSE_USER
  2829. );
  2830. $question_id = intval($question_id);
  2831. $answer_id = intval($answer_id);
  2832. $exercise_id = intval($exercise_id);
  2833. $courseId = api_get_course_int_id($course_code);
  2834. $course_code = Database::escape_string($course_code);
  2835. $session_id = intval($session_id);
  2836. switch ($question_type) {
  2837. case FILL_IN_BLANKS:
  2838. $answer_condition = "";
  2839. $select_condition = " e.exe_id, answer ";
  2840. break;
  2841. case MATCHING:
  2842. default:
  2843. $answer_condition = " answer = $answer_id AND ";
  2844. $select_condition = " DISTINCT exe_user_id ";
  2845. }
  2846. if (empty($session_id)) {
  2847. $courseCondition = "
  2848. INNER JOIN $courseUser cu
  2849. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2850. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT;
  2851. } else {
  2852. $courseCondition = "
  2853. INNER JOIN $courseUserSession cu
  2854. ON cu.c_id = a.c_id AND cu.user_id = exe_user_id";
  2855. $courseConditionWhere = " AND cu.status = 0 ";
  2856. }
  2857. $sql = "SELECT $select_condition
  2858. FROM $track_exercises e
  2859. INNER JOIN $track_attempt a
  2860. ON (
  2861. a.exe_id = e.exe_id AND
  2862. e.c_id = a.c_id AND
  2863. e.session_id = a.session_id
  2864. )
  2865. INNER JOIN $courseTable c
  2866. ON c.code = a.course_code
  2867. $courseCondition
  2868. WHERE
  2869. exe_exo_id = $exercise_id AND
  2870. a.c_id = $courseId AND
  2871. e.session_id = $session_id AND
  2872. $answer_condition
  2873. question_id = $question_id AND
  2874. e.status = ''
  2875. $courseConditionWhere
  2876. ";
  2877. $result = Database::query($sql);
  2878. $return = 0;
  2879. if ($result) {
  2880. $good_answers = 0;
  2881. switch ($question_type) {
  2882. case FILL_IN_BLANKS:
  2883. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2884. $fill_blank = self::check_fill_in_blanks(
  2885. $correct_answer,
  2886. $row['answer']
  2887. );
  2888. if (isset($fill_blank[$current_answer]) && $fill_blank[$current_answer] == 1) {
  2889. $good_answers++;
  2890. }
  2891. }
  2892. return $good_answers;
  2893. break;
  2894. case MATCHING:
  2895. default:
  2896. $return = Database::num_rows($result);
  2897. }
  2898. }
  2899. return $return;
  2900. }
  2901. /**
  2902. * @param array $answer
  2903. * @param string $user_answer
  2904. * @return array
  2905. */
  2906. public static function check_fill_in_blanks($answer, $user_answer)
  2907. {
  2908. // the question is encoded like this
  2909. // [A] B [C] D [E] F::10,10,10@1
  2910. // number 1 before the "@" means that is a switchable fill in blank question
  2911. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  2912. // means that is a normal fill blank question
  2913. // first we explode the "::"
  2914. $pre_array = explode('::', $answer);
  2915. // is switchable fill blank or not
  2916. $last = count($pre_array) - 1;
  2917. $is_set_switchable = explode('@', $pre_array[$last]);
  2918. $switchable_answer_set = false;
  2919. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  2920. $switchable_answer_set = true;
  2921. }
  2922. $answer = '';
  2923. for ($k = 0; $k < $last; $k++) {
  2924. $answer .= $pre_array[$k];
  2925. }
  2926. // splits weightings that are joined with a comma
  2927. $answerWeighting = explode(',', $is_set_switchable[0]);
  2928. // we save the answer because it will be modified
  2929. //$temp = $answer;
  2930. $temp = $answer;
  2931. $answer = '';
  2932. $j = 0;
  2933. //initialise answer tags
  2934. $user_tags = $correct_tags = $real_text = array();
  2935. // the loop will stop at the end of the text
  2936. while (1) {
  2937. // quits the loop if there are no more blanks (detect '[')
  2938. if (($pos = api_strpos($temp, '[')) === false) {
  2939. // adds the end of the text
  2940. $answer = $temp;
  2941. /* // Deprecated code
  2942. // TeX parsing - replacement of texcode tags
  2943. $texstring = api_parse_tex($texstring);
  2944. $answer = str_replace("{texcode}", $texstring, $answer);
  2945. */
  2946. $real_text[] = $answer;
  2947. break; //no more "blanks", quit the loop
  2948. }
  2949. // adds the piece of text that is before the blank
  2950. //and ends with '[' into a general storage array
  2951. $real_text[] = api_substr($temp, 0, $pos + 1);
  2952. $answer .= api_substr($temp, 0, $pos + 1);
  2953. //take the string remaining (after the last "[" we found)
  2954. $temp = api_substr($temp, $pos + 1);
  2955. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  2956. if (($pos = api_strpos($temp, ']')) === false) {
  2957. // adds the end of the text
  2958. $answer .= $temp;
  2959. break;
  2960. }
  2961. $str = $user_answer;
  2962. preg_match_all('#\[([^[]*)\]#', $str, $arr);
  2963. $str = str_replace('\r\n', '', $str);
  2964. $choice = $arr[1];
  2965. $tmp = api_strrpos($choice[$j], ' / ');
  2966. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  2967. $choice[$j] = trim($choice[$j]);
  2968. //Needed to let characters ' and " to work as part of an answer
  2969. $choice[$j] = stripslashes($choice[$j]);
  2970. $user_tags[] = api_strtolower($choice[$j]);
  2971. //put the contents of the [] answer tag into correct_tags[]
  2972. $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  2973. $j++;
  2974. $temp = api_substr($temp, $pos + 1);
  2975. }
  2976. $answer = '';
  2977. $real_correct_tags = $correct_tags;
  2978. $chosen_list = array();
  2979. $good_answer = array();
  2980. for ($i = 0; $i < count($real_correct_tags); $i++) {
  2981. if (!$switchable_answer_set) {
  2982. //needed to parse ' and " characters
  2983. $user_tags[$i] = stripslashes($user_tags[$i]);
  2984. if ($correct_tags[$i] == $user_tags[$i]) {
  2985. $good_answer[$correct_tags[$i]] = 1;
  2986. } elseif (!empty ($user_tags[$i])) {
  2987. $good_answer[$correct_tags[$i]] = 0;
  2988. } else {
  2989. $good_answer[$correct_tags[$i]] = 0;
  2990. }
  2991. } else {
  2992. // switchable fill in the blanks
  2993. if (in_array($user_tags[$i], $correct_tags)) {
  2994. $correct_tags = array_diff($correct_tags, $chosen_list);
  2995. $good_answer[$correct_tags[$i]] = 1;
  2996. } elseif (!empty ($user_tags[$i])) {
  2997. $good_answer[$correct_tags[$i]] = 0;
  2998. } else {
  2999. $good_answer[$correct_tags[$i]] = 0;
  3000. }
  3001. }
  3002. // adds the correct word, followed by ] to close the blank
  3003. $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
  3004. if (isset ($real_text[$i + 1])) {
  3005. $answer .= $real_text[$i + 1];
  3006. }
  3007. }
  3008. return $good_answer;
  3009. }
  3010. /**
  3011. * @param int $exercise_id
  3012. * @param string $course_code
  3013. * @param int $session_id
  3014. * @return int
  3015. */
  3016. public static function get_number_students_finish_exercise(
  3017. $exercise_id,
  3018. $course_code,
  3019. $session_id
  3020. ) {
  3021. $track_exercises = Database::get_main_table(
  3022. TABLE_STATISTIC_TRACK_E_EXERCISES
  3023. );
  3024. $track_attempt = Database::get_main_table(
  3025. TABLE_STATISTIC_TRACK_E_ATTEMPT
  3026. );
  3027. $exercise_id = intval($exercise_id);
  3028. $course_code = Database::escape_string($course_code);
  3029. $session_id = intval($session_id);
  3030. $sql = "SELECT DISTINCT exe_user_id
  3031. FROM $track_exercises e
  3032. INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id)
  3033. WHERE
  3034. exe_exo_id = $exercise_id AND
  3035. course_code = '$course_code' AND
  3036. e.session_id = $session_id AND
  3037. status = ''";
  3038. $result = Database::query($sql);
  3039. $return = 0;
  3040. if ($result) {
  3041. $return = Database::num_rows($result);
  3042. }
  3043. return $return;
  3044. }
  3045. /**
  3046. * @param string $in_name is the name and the id of the <select>
  3047. * @param string $in_default default value for option
  3048. * @param string $in_onchange
  3049. * @return string the html code of the <select>
  3050. */
  3051. public static function displayGroupMenu($in_name, $in_default, $in_onchange = "")
  3052. {
  3053. // check the default value of option
  3054. $tabSelected = array($in_default => " selected='selected' ");
  3055. $res = "";
  3056. $res .= "<select name='$in_name' id='$in_name' onchange='" . $in_onchange . "' >";
  3057. $res .= "<option value='-1'" . $tabSelected["-1"] . ">-- " . get_lang(
  3058. 'AllGroups'
  3059. ) . " --</option>";
  3060. $res .= "<option value='0'" . $tabSelected["0"] . ">- " . get_lang(
  3061. 'NotInAGroup'
  3062. ) . " -</option>";
  3063. $tabGroups = GroupManager::get_group_list();
  3064. $currentCatId = 0;
  3065. for ($i = 0; $i < count($tabGroups); $i++) {
  3066. $tabCategory = GroupManager::get_category_from_group(
  3067. $tabGroups[$i]["id"]
  3068. );
  3069. if ($tabCategory["id"] != $currentCatId) {
  3070. $res .= "<option value='-1' disabled='disabled'>" . $tabCategory["title"] . "</option>";
  3071. $currentCatId = $tabCategory["id"];
  3072. }
  3073. $res .= "<option " . $tabSelected[$tabGroups[$i]["id"]] . "style='margin-left:40px' value='" . $tabGroups[$i]["id"] . "'>" . $tabGroups[$i]["name"] . "</option>";
  3074. }
  3075. $res .= "</select>";
  3076. return $res;
  3077. }
  3078. /**
  3079. * Return a list of group for user with user_id=in_userid separated with in_separator
  3080. * @deprecated ?
  3081. */
  3082. public static function displayGroupsForUser($in_separator, $in_userid)
  3083. {
  3084. $res = implode(
  3085. $in_separator,
  3086. GroupManager::get_user_group_name($in_userid)
  3087. );
  3088. if ($res == "") {
  3089. $res = "<div style='text-align:center'>-</div>";
  3090. }
  3091. return $res;
  3092. }
  3093. /**
  3094. * @param int $exe_id
  3095. */
  3096. public static function create_chat_exercise_session($exe_id)
  3097. {
  3098. if (!isset($_SESSION['current_exercises'])) {
  3099. $_SESSION['current_exercises'] = array();
  3100. }
  3101. $_SESSION['current_exercises'][$exe_id] = true;
  3102. }
  3103. /**
  3104. * @param int $exe_id
  3105. */
  3106. public static function delete_chat_exercise_session($exe_id)
  3107. {
  3108. if (isset($_SESSION['current_exercises'])) {
  3109. $_SESSION['current_exercises'][$exe_id] = false;
  3110. }
  3111. }
  3112. /**
  3113. * Display the exercise results
  3114. * @param Exercise $objExercise
  3115. * @param int $exe_id
  3116. * @param bool $save_user_result save users results (true) or just show the results (false)
  3117. */
  3118. public static function display_question_list_by_attempt(
  3119. $objExercise,
  3120. $exe_id,
  3121. $save_user_result = false
  3122. ) {
  3123. global $origin;
  3124. // Getting attempt info
  3125. $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id(
  3126. $exe_id
  3127. );
  3128. // Getting question list
  3129. $question_list = array();
  3130. if (!empty($exercise_stat_info['data_tracking'])) {
  3131. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  3132. } else {
  3133. // Try getting the question list only if save result is off
  3134. if ($save_user_result == false) {
  3135. $question_list = $objExercise->get_validated_question_list();
  3136. }
  3137. }
  3138. $counter = 1;
  3139. $total_score = $total_weight = 0;
  3140. $exercise_content = null;
  3141. // Hide results
  3142. $show_results = false;
  3143. $show_only_score = false;
  3144. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) {
  3145. $show_results = true;
  3146. }
  3147. if (in_array(
  3148. $objExercise->results_disabled,
  3149. array(
  3150. RESULT_DISABLE_SHOW_SCORE_ONLY,
  3151. RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES
  3152. )
  3153. )
  3154. ) {
  3155. $show_only_score = true;
  3156. }
  3157. // Not display expected answer, but score, and feedback
  3158. $show_all_but_expected_answer = false;
  3159. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY &&
  3160. $objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END
  3161. ) {
  3162. $show_all_but_expected_answer = true;
  3163. $show_results = true;
  3164. $show_only_score = false;
  3165. }
  3166. if ($show_results || $show_only_score) {
  3167. $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
  3168. //Shows exercise header
  3169. echo $objExercise->show_exercise_result_header(
  3170. $user_info,
  3171. api_convert_and_format_date(
  3172. $exercise_stat_info['start_date'],
  3173. DATE_TIME_FORMAT_LONG
  3174. ),
  3175. $exercise_stat_info['duration'],
  3176. $exercise_stat_info['user_ip']
  3177. );
  3178. }
  3179. // Display text when test is finished #4074 and for LP #4227
  3180. $end_of_message = $objExercise->selectTextWhenFinished();
  3181. if (!empty($end_of_message)) {
  3182. Display::display_normal_message($end_of_message, false);
  3183. echo "<div class='clear'>&nbsp;</div>";
  3184. }
  3185. $question_list_answers = array();
  3186. $media_list = array();
  3187. $category_list = array();
  3188. // Loop over all question to show results for each of them, one by one
  3189. if (!empty($question_list)) {
  3190. foreach ($question_list as $questionId) {
  3191. // creates a temporary Question object
  3192. $objQuestionTmp = Question::read($questionId);
  3193. // This variable came from exercise_submit_modal.php
  3194. ob_start();
  3195. // We're inside *one* question. Go through each possible answer for this question
  3196. $result = $objExercise->manage_answer(
  3197. $exercise_stat_info['exe_id'],
  3198. $questionId,
  3199. null,
  3200. 'exercise_result',
  3201. array(),
  3202. $save_user_result,
  3203. true,
  3204. $show_results,
  3205. $objExercise->selectPropagateNeg(),
  3206. array()
  3207. );
  3208. if (empty($result)) {
  3209. continue;
  3210. }
  3211. // In case of global score, make sure the calculated total score is integer
  3212. /*if (!is_int($result['score'])) {
  3213. $result['score'] = round($result['score']);
  3214. }*/
  3215. $total_score += $result['score'];
  3216. $total_weight += $result['weight'];
  3217. $question_list_answers[] = array(
  3218. 'question' => $result['open_question'],
  3219. 'answer' => $result['open_answer'],
  3220. 'answer_type' => $result['answer_type']
  3221. );
  3222. $my_total_score = $result['score'];
  3223. $my_total_weight = $result['weight'];
  3224. // Category report
  3225. $category_was_added_for_this_test = false;
  3226. if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) {
  3227. $category_list[$objQuestionTmp->category]['score'] += $my_total_score;
  3228. $category_list[$objQuestionTmp->category]['total'] += $my_total_weight;
  3229. $category_was_added_for_this_test = true;
  3230. }
  3231. if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) {
  3232. foreach ($objQuestionTmp->category_list as $category_id) {
  3233. $category_list[$category_id]['score'] += $my_total_score;
  3234. $category_list[$category_id]['total'] += $my_total_weight;
  3235. $category_was_added_for_this_test = true;
  3236. }
  3237. }
  3238. // No category for this question!
  3239. if ($category_was_added_for_this_test == false) {
  3240. if (!isset($category_list['none']['score'])) {
  3241. $category_list['none']['score'] = 0;
  3242. }
  3243. if (!isset($category_list['none']['total'])) {
  3244. $category_list['none']['total'] = 0;
  3245. }
  3246. $category_list['none']['score'] += $my_total_score;
  3247. $category_list['none']['total'] += $my_total_weight;
  3248. }
  3249. if ($objExercise->selectPropagateNeg(
  3250. ) == 0 && $my_total_score < 0
  3251. ) {
  3252. $my_total_score = 0;
  3253. }
  3254. $comnt = null;
  3255. if ($show_results) {
  3256. $comnt = Event::get_comments($exe_id, $questionId);
  3257. if (!empty($comnt)) {
  3258. echo '<b>' . get_lang('Feedback') . '</b>';
  3259. echo '<div id="question_feedback">' . $comnt . '</div>';
  3260. }
  3261. }
  3262. if ($show_results) {
  3263. $score = array(
  3264. 'result' => get_lang('Score') . " : " . self::show_score(
  3265. $my_total_score,
  3266. $my_total_weight,
  3267. false,
  3268. true
  3269. ),
  3270. 'pass' => $my_total_score >= $my_total_weight ? true : false,
  3271. 'score' => $my_total_score,
  3272. 'weight' => $my_total_weight,
  3273. 'comments' => $comnt,
  3274. );
  3275. } else {
  3276. $score = array();
  3277. }
  3278. $contents = ob_get_clean();
  3279. $question_content = '<div class="question_row">';
  3280. if ($show_results) {
  3281. $show_media = false;
  3282. /*if ($objQuestionTmp->parent_id != 0 && !in_array($objQuestionTmp->parent_id, $media_list)) {
  3283. $show_media = true;
  3284. $media_list[] = $objQuestionTmp->parent_id;
  3285. }*/
  3286. //Shows question title an description
  3287. $question_content .= $objQuestionTmp->return_header(
  3288. null,
  3289. $counter,
  3290. $score
  3291. );
  3292. }
  3293. $counter++;
  3294. $question_content .= $contents;
  3295. $question_content .= '</div>';
  3296. $exercise_content .= $question_content;
  3297. } // end foreach() block that loops over all questions
  3298. }
  3299. $total_score_text = null;
  3300. if ($origin != 'learnpath') {
  3301. if ($show_results || $show_only_score) {
  3302. $total_score_text .= '<div class="question_row">';
  3303. $total_score_text .= self::get_question_ribbon(
  3304. $objExercise,
  3305. $total_score,
  3306. $total_weight,
  3307. true
  3308. );
  3309. $total_score_text .= '</div>';
  3310. }
  3311. }
  3312. if (!empty($category_list) && ($show_results || $show_only_score)) {
  3313. //Adding total
  3314. $category_list['total'] = array(
  3315. 'score' => $total_score,
  3316. 'total' => $total_weight
  3317. );
  3318. echo TestCategory::get_stats_table_by_attempt(
  3319. $objExercise->id,
  3320. $category_list
  3321. );
  3322. }
  3323. if ($show_all_but_expected_answer) {
  3324. $exercise_content .= "<div class='normal-message'>" . get_lang(
  3325. "ExerciseWithFeedbackWithoutCorrectionComment"
  3326. ) . "</div>";
  3327. }
  3328. // Remove audio auto play from questions on results page - refs BT#7939
  3329. $exercise_content = preg_replace(
  3330. ['/autoplay[\=\".+\"]+/','/autostart[\=\".+\"]+/'],
  3331. '',
  3332. $exercise_content
  3333. );
  3334. echo $total_score_text;
  3335. echo $exercise_content;
  3336. if (!$show_only_score) {
  3337. echo $total_score_text;
  3338. }
  3339. if ($save_user_result) {
  3340. // Tracking of results
  3341. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  3342. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  3343. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  3344. if (api_is_allowed_to_session_edit()) {
  3345. Event::update_event_exercice(
  3346. $exercise_stat_info['exe_id'],
  3347. $objExercise->selectId(),
  3348. $total_score,
  3349. $total_weight,
  3350. api_get_session_id(),
  3351. $learnpath_id,
  3352. $learnpath_item_id,
  3353. $learnpath_item_view_id,
  3354. $exercise_stat_info['exe_duration'],
  3355. $question_list,
  3356. '',
  3357. array()
  3358. );
  3359. }
  3360. // Send notification ..
  3361. if (!api_is_allowed_to_edit(null, true) && !apiIsExcludedUserType()
  3362. ) {
  3363. if (api_get_course_setting(
  3364. 'email_alert_manager_on_new_quiz'
  3365. ) == 1
  3366. ) {
  3367. $objExercise->send_mail_notification_for_exam(
  3368. $question_list_answers,
  3369. $origin,
  3370. $exe_id
  3371. );
  3372. }
  3373. $objExercise->send_notification_for_open_questions(
  3374. $question_list_answers,
  3375. $origin,
  3376. $exe_id
  3377. );
  3378. $objExercise->send_notification_for_oral_questions(
  3379. $question_list_answers,
  3380. $origin,
  3381. $exe_id
  3382. );
  3383. }
  3384. }
  3385. }
  3386. /**
  3387. * @param Exercise $objExercise
  3388. * @param float $score
  3389. * @param float $weight
  3390. * @param bool $check_pass_percentage
  3391. * @return string
  3392. */
  3393. public static function get_question_ribbon(
  3394. $objExercise,
  3395. $score,
  3396. $weight,
  3397. $check_pass_percentage = false
  3398. ) {
  3399. $ribbon = '<div class="ribbon">';
  3400. if ($check_pass_percentage) {
  3401. $is_success = self::is_success_exercise_result(
  3402. $score,
  3403. $weight,
  3404. $objExercise->selectPassPercentage()
  3405. );
  3406. // Color the final test score if pass_percentage activated
  3407. $ribbon_total_success_or_error = "";
  3408. if (self::is_pass_pourcentage_enabled(
  3409. $objExercise->selectPassPercentage()
  3410. )) {
  3411. if ($is_success) {
  3412. $ribbon_total_success_or_error = ' ribbon-total-success';
  3413. } else {
  3414. $ribbon_total_success_or_error = ' ribbon-total-error';
  3415. }
  3416. }
  3417. $ribbon .= '<div class="rib rib-total ' . $ribbon_total_success_or_error . '">';
  3418. } else {
  3419. $ribbon .= '<div class="rib rib-total">';
  3420. }
  3421. $ribbon .= '<h3>' . get_lang('YourTotalScore') . ":&nbsp;";
  3422. $ribbon .= self::show_score($score, $weight, false, true);
  3423. $ribbon .= '</h3>';
  3424. $ribbon .= '</div>';
  3425. if ($check_pass_percentage) {
  3426. $ribbon .= self::show_success_message(
  3427. $score,
  3428. $weight,
  3429. $objExercise->selectPassPercentage()
  3430. );
  3431. }
  3432. $ribbon .= '</div>';
  3433. return $ribbon;
  3434. }
  3435. /**
  3436. * @param int $countLetter
  3437. * @return mixed
  3438. */
  3439. public static function detectInputAppropriateClass($countLetter)
  3440. {
  3441. $limits = array(
  3442. 0 => 'input-mini',
  3443. 10 => 'input-mini',
  3444. 15 => 'input-medium',
  3445. 20 => 'input-xlarge',
  3446. 40 => 'input-xlarge',
  3447. 60 => 'input-xxlarge',
  3448. 100 => 'input-xxlarge',
  3449. 200 => 'input-xxlarge',
  3450. );
  3451. foreach ($limits as $size => $item) {
  3452. if ($countLetter <= $size) {
  3453. return $item;
  3454. }
  3455. }
  3456. return $limits[0];
  3457. }
  3458. }