exercise.class.php 130 KB

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