exercise.lib.php 149 KB

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