exercise.class.php 149 KB

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