exercise.class.php 135 KB

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