exercise.class.php 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630
  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);
  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);
  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;