exercise.class.php 112 KB

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