exercise.class.php 146 KB

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