exercise.class.php 124 KB

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