exercise.class.php 138 KB

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