exercise.class.php 144 KB

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