exercise.class.php 187 KB

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