exercise.lib.php 149 KB

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