exercise.class.php 127 KB

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