exercise.class.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. <?php
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2008 Dokeos SPRL
  6. For a full list of contributors, see "credits.txt".
  7. The full license can be read in "license.txt".
  8. This program is free software; you can redistribute it and/or
  9. modify it under the terms of the GNU General Public License
  10. as published by the Free Software Foundation; either version 2
  11. of the License, or (at your option) any later version.
  12. See the GNU General Public License for more details.
  13. Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
  14. Mail: info@dokeos.com
  15. ==============================================================================
  16. */
  17. /**
  18. * Exercise class: This class allows to instantiate an object of type Exercise
  19. * @package dokeos.exercise
  20. * @author Olivier Brouckaert
  21. * @version $Id: exercise.class.php 18235 2009-02-04 16:34:55Z juliomontoya $
  22. */
  23. if(!class_exists('Exercise')):
  24. class Exercise
  25. {
  26. var $id;
  27. var $exercise;
  28. var $description;
  29. var $sound;
  30. var $type;
  31. var $random;
  32. var $active;
  33. var $timeLimit;
  34. var $attempts;
  35. var $feedbacktype;
  36. var $end_time;
  37. var $start_time;
  38. var $questionList; // array with the list of this exercise's questions
  39. /**
  40. * constructor of the class
  41. *
  42. * @author - Olivier Brouckaert
  43. */
  44. function Exercise()
  45. {
  46. $this->id=0;
  47. $this->exercise='';
  48. $this->description='';
  49. $this->sound='';
  50. $this->type=1;
  51. $this->random=0;
  52. $this->active=1;
  53. $this->questionList=array();
  54. $this->timeLimit = 0;
  55. $this->end_time = '0000-00-00 00:00:00';
  56. $this->start_time = '0000-00-00 00:00:00';
  57. }
  58. /**
  59. * reads exercise informations from the data base
  60. *
  61. * @author - Olivier Brouckaert
  62. * @param - integer $id - exercise ID
  63. * @return - boolean - true if exercise exists, otherwise false
  64. */
  65. function read($id)
  66. {
  67. global $_course;
  68. global $_configuration;
  69. global $questionList;
  70. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  71. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  72. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  73. #$TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  74. $sql="SELECT title,description,sound,type,random,active, results_disabled, max_attempt,start_time,end_time,feedback_type FROM $TBL_EXERCICES WHERE id='".Database::escape_string($id)."'";
  75. $result=api_sql_query($sql,__FILE__,__LINE__);
  76. // if the exercise has been found
  77. if($object=Database::fetch_object($result))
  78. {
  79. $this->id=$id;
  80. $this->exercise=$object->title;
  81. $this->description=$object->description;
  82. $this->sound=$object->sound;
  83. $this->type=$object->type;
  84. $this->random=$object->random;
  85. $this->active=$object->active;
  86. $this->results_disabled =$object->results_disabled;
  87. $this->attempts = $object->max_attempt;
  88. $this->feedbacktype = $object->feedback_type;
  89. $this->end_time = $object->end_time;
  90. $this->start_time = $object->start_time;
  91. $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";
  92. $result=api_sql_query($sql,__FILE__,__LINE__);
  93. // fills the array with the question ID for this exercise
  94. // the key of the array is the question position
  95. while($object=Database::fetch_object($result))
  96. {
  97. // makes sure that the question position is unique
  98. while(isset($this->questionList[$object->question_order]))
  99. {
  100. $object->question_order++;
  101. }
  102. $this->questionList[$object->question_order]=$object->question_id;
  103. }
  104. //var_dump($this->end_time,$object->start_time);
  105. if($this->random > 0){
  106. $this->questionList = $this->selectRandomList();
  107. }
  108. //overload questions list with recorded questions list
  109. //load questions only for exercises of type 'one question per page'
  110. //this is needed only is there is no questions
  111. //
  112. if($this->type == 2 && $_configuration['live_exercise_tracking']==true && $_SERVER['REQUEST_METHOD']!='POST' && defined('QUESTION_LIST_ALREADY_LOGGED'))
  113. {
  114. //if(empty($_SESSION['questionList']))
  115. $this->questionList = $questionList;
  116. }
  117. return true;
  118. }
  119. // exercise not found
  120. return false;
  121. }
  122. /**
  123. * returns the exercise ID
  124. *
  125. * @author - Olivier Brouckaert
  126. * @return - integer - exercise ID
  127. */
  128. function selectId()
  129. {
  130. return $this->id;
  131. }
  132. /**
  133. * returns the exercise title
  134. *
  135. * @author - Olivier Brouckaert
  136. * @return - string - exercise title
  137. */
  138. function selectTitle()
  139. {
  140. return $this->exercise;
  141. }
  142. /**
  143. * returns the number of attempts setted
  144. *
  145. * @return - numeric - exercise attempts
  146. */
  147. function selectAttempts()
  148. {
  149. return $this->attempts;
  150. }
  151. /** returns the number of FeedbackType *
  152. * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  153. * @return - numeric - exercise attempts
  154. */
  155. function selectFeedbackType()
  156. {
  157. return $this->feedbacktype;
  158. }
  159. /**
  160. * returns the time limit
  161. */
  162. function selectTimeLimit()
  163. {
  164. return $this->timeLimit;
  165. }
  166. /**
  167. * returns the exercise description
  168. *
  169. * @author - Olivier Brouckaert
  170. * @return - string - exercise description
  171. */
  172. function selectDescription()
  173. {
  174. return $this->description;
  175. }
  176. /**
  177. * returns the exercise sound file
  178. *
  179. * @author - Olivier Brouckaert
  180. * @return - string - exercise description
  181. */
  182. function selectSound()
  183. {
  184. return $this->sound;
  185. }
  186. /**
  187. * returns the exercise type
  188. *
  189. * @author - Olivier Brouckaert
  190. * @return - integer - exercise type
  191. */
  192. function selectType()
  193. {
  194. return $this->type;
  195. }
  196. /**
  197. * tells if questions are selected randomly, and if so returns the draws
  198. *
  199. * @author - Olivier Brouckaert
  200. * @return - integer - 0 if not random, otherwise the draws
  201. */
  202. function isRandom()
  203. {
  204. if($this->random > 0){
  205. return true;
  206. }
  207. else{
  208. return false;
  209. }
  210. }
  211. /**
  212. * Same as isRandom() but has a name applied to values different than 0 or 1
  213. */
  214. function getShuffle()
  215. {
  216. return $this->random;
  217. }
  218. /**
  219. * returns the exercise status (1 = enabled ; 0 = disabled)
  220. *
  221. * @author - Olivier Brouckaert
  222. * @return - boolean - true if enabled, otherwise false
  223. */
  224. function selectStatus()
  225. {
  226. return $this->active;
  227. }
  228. /**
  229. * returns the array with the question ID list
  230. *
  231. * @author - Olivier Brouckaert
  232. * @return - array - question ID list
  233. */
  234. function selectQuestionList()
  235. {
  236. return $this->questionList;
  237. }
  238. /**
  239. * returns the number of questions in this exercise
  240. *
  241. * @author - Olivier Brouckaert
  242. * @return - integer - number of questions
  243. */
  244. function selectNbrQuestions()
  245. {
  246. return sizeof($this->questionList);
  247. }
  248. /**
  249. * selects questions randomly in the question list
  250. *
  251. * @author - Olivier Brouckaert
  252. * @return - array - if the exercise is not set to take questions randomly, returns the question list
  253. * without randomizing, otherwise, returns the list with questions selected randomly
  254. */
  255. function selectRandomList()
  256. {
  257. $nbQuestions = $this->selectNbrQuestions();
  258. $temp_list = $this->questionList;
  259. shuffle($temp_list);
  260. return array_combine(range(1,$nbQuestions),$temp_list);
  261. $nbQuestions = $this->selectNbrQuestions();
  262. //Not a random exercise, or if there are not at least 2 questions
  263. if($this->random == 0 || $nbQuestions < 2)
  264. {
  265. return $this->questionList;
  266. }
  267. $randQuestionList = array();
  268. $alreadyChosen = array();
  269. for($i=0; $i < $this->random; $i++)
  270. {
  271. if($i < $nbQuestions){
  272. do
  273. {
  274. $rand=rand(1,$nbQuestions);
  275. }
  276. while(in_array($rand,$alreadyChosen));
  277. $alreadyChosen[]=$rand;
  278. $randQuestionList[$rand] = $this->questionList[$rand];
  279. }
  280. }
  281. return $randQuestionList;
  282. }
  283. /**
  284. * returns 'true' if the question ID is in the question list
  285. *
  286. * @author - Olivier Brouckaert
  287. * @param - integer $questionId - question ID
  288. * @return - boolean - true if in the list, otherwise false
  289. */
  290. function isInList($questionId)
  291. {
  292. return in_array($questionId,$this->questionList);
  293. }
  294. /**
  295. * changes the exercise title
  296. *
  297. * @author - Olivier Brouckaert
  298. * @param - string $title - exercise title
  299. */
  300. function updateTitle($title)
  301. {
  302. $this->exercise=$title;
  303. }
  304. /**
  305. * changes the exercise max attempts
  306. *
  307. * @param - numeric $attempts - exercise max attempts
  308. */
  309. function updateAttempts($attempts)
  310. {
  311. $this->attempts=$attempts;
  312. }
  313. /**
  314. * changes the exercise feedback type
  315. *
  316. * @param - numeric $attempts - exercise max attempts
  317. */
  318. function updateFeedbackType($feedback_type)
  319. {
  320. $this->feedbacktype=$feedback_type;
  321. }
  322. /**
  323. * changes the exercise description
  324. *
  325. * @author - Olivier Brouckaert
  326. * @param - string $description - exercise description
  327. */
  328. function updateDescription($description)
  329. {
  330. $this->description=$description;
  331. }
  332. /**
  333. * changes the exercise sound file
  334. *
  335. * @author - Olivier Brouckaert
  336. * @param - string $sound - exercise sound file
  337. * @param - string $delete - ask to delete the file
  338. */
  339. function updateSound($sound,$delete)
  340. {
  341. global $audioPath, $documentPath,$_course, $_user;
  342. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  343. $TBL_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  344. if($sound['size'] && (strstr($sound['type'],'audio') || strstr($sound['type'],'video')))
  345. {
  346. $this->sound=$sound['name'];
  347. if(@move_uploaded_file($sound['tmp_name'],$audioPath.'/'.$this->sound))
  348. {
  349. $query="SELECT 1 FROM $TBL_DOCUMENT "
  350. ." WHERE path='".str_replace($documentPath,'',$audioPath).'/'.$this->sound."'";
  351. $result=api_sql_query($query,__FILE__,__LINE__);
  352. if(!mysql_num_rows($result))
  353. {
  354. /*$query="INSERT INTO $TBL_DOCUMENT(path,filetype) VALUES "
  355. ." ('".str_replace($documentPath,'',$audioPath).'/'.$this->sound."','file')";
  356. api_sql_query($query,__FILE__,__LINE__);*/
  357. $id = add_document($_course,str_replace($documentPath,'',$audioPath).'/'.$this->sound,'file',$sound['size'],$sound['name']);
  358. //$id = Database::get_last_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. api_sql_query($query,__FILE__,__LINE__);*/
  367. api_item_property_update($_course, TOOL_DOCUMENT, $id, 'DocumentAdded',$_user['user_id']);
  368. item_property_update_on_folder($_course,str_replace($documentPath,'',$audioPath),$_user['user_id']);
  369. }
  370. }
  371. }
  372. elseif($delete && is_file($audioPath.'/'.$this->sound))
  373. {
  374. $this->sound='';
  375. }
  376. }
  377. /**
  378. * changes the exercise type
  379. *
  380. * @author - Olivier Brouckaert
  381. * @param - integer $type - exercise type
  382. */
  383. function updateType($type)
  384. {
  385. $this->type=$type;
  386. }
  387. /**
  388. * sets to 0 if questions are not selected randomly
  389. * if questions are selected randomly, sets the draws
  390. *
  391. * @author - Olivier Brouckaert
  392. * @param - integer $random - 0 if not random, otherwise the draws
  393. */
  394. function setRandom($random)
  395. {
  396. $this->random=$random;
  397. }
  398. /**
  399. * enables the exercise
  400. *
  401. * @author - Olivier Brouckaert
  402. */
  403. function enable()
  404. {
  405. $this->active=1;
  406. }
  407. /**
  408. * disables the exercise
  409. *
  410. * @author - Olivier Brouckaert
  411. */
  412. function disable()
  413. {
  414. $this->active=0;
  415. }
  416. function disable_results()
  417. {
  418. $this->results_disabled = true;
  419. }
  420. function enable_results()
  421. {
  422. $this->results_disabled = false;
  423. }
  424. /**
  425. * updates the exercise in the data base
  426. *
  427. * @author - Olivier Brouckaert
  428. */
  429. function save()
  430. {
  431. global $_course,$_user;
  432. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  433. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  434. $TBL_QUIZ_QUESTION= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  435. $id=$this->id;
  436. $exercise=addslashes($this->exercise);
  437. $description=addslashes($this->description);
  438. $sound=addslashes($this->sound);
  439. $type=$this->type;
  440. $attempts=$this->attempts;
  441. $feedbacktype=$this->feedbacktype;
  442. $random=$this->random;
  443. $active=$this->active;
  444. $results_disabled = intval($this->results_disabled);
  445. $start_time = Database::escape_string($this->start_time);
  446. $end_time = Database::escape_string($this->end_time);
  447. // exercise already exists
  448. if($id)
  449. {
  450. $sql="UPDATE $TBL_EXERCICES SET
  451. start_time='$start_time',end_time='$end_time',
  452. title='".Database::escape_string($exercise)."',
  453. description='".Database::escape_string($description)."',
  454. sound='".Database::escape_string($sound)."',
  455. type='".Database::escape_string($type)."',
  456. random='".Database::escape_string($random)."',
  457. active='".Database::escape_string($active)."',
  458. feedback_type='".Database::escape_string($feedbacktype)."',
  459. max_attempt='".Database::escape_string($attempts)."', " .
  460. "results_disabled='".Database::escape_string($results_disabled)."'
  461. WHERE id='".Database::escape_string($id)."'";
  462. api_sql_query($sql,__FILE__,__LINE__);
  463. // update into the item_property table
  464. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizUpdated',$_user['user_id']);
  465. if (api_get_setting('search_enabled')=='true') {
  466. $this -> search_engine_edit();
  467. }
  468. }
  469. // creates a new exercise
  470. else
  471. {
  472. $sql="INSERT INTO $TBL_EXERCICES(start_time,end_time,title,description,sound,type,random,active, results_disabled, max_attempt,feedback_type)
  473. VALUES(
  474. '$start_time','$end_time',
  475. '".Database::escape_string($exercise)."',
  476. '".Database::escape_string($description)."',
  477. '".Database::escape_string($sound)."',
  478. '".Database::escape_string($type)."',
  479. '".Database::escape_string($random)."',
  480. '".Database::escape_string($active)."',
  481. '".Database::escape_string($results_disabled)."',
  482. '".Database::escape_string($attempts)."',
  483. '".Database::escape_string($feedbacktype)."'
  484. )";
  485. api_sql_query($sql,__FILE__,__LINE__);
  486. $this->id=mysql_insert_id();
  487. // insert into the item_property table
  488. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizAdded',$_user['user_id']);
  489. if (api_get_setting('search_enabled')=='true') {
  490. $this -> search_engine_save();
  491. }
  492. }
  493. // updates the question position
  494. $this->update_question_positions();
  495. }
  496. function update_question_positions() {
  497. // updates the question position
  498. $TBL_QUIZ_QUESTION= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  499. foreach($this->questionList as $position=>$questionId)
  500. {
  501. //$sql="UPDATE $TBL_QUESTIONS SET position='".Database::escape_string($position)."' WHERE id='".Database::escape_string($questionId)."'";
  502. $sql="UPDATE $TBL_QUIZ_QUESTION SET question_order='".Database::escape_string($position)."' " .
  503. "WHERE question_id='".Database::escape_string($questionId)."' and exercice_id=".Database::escape_string($this->id)."";
  504. api_sql_query($sql,__FILE__,__LINE__);
  505. }
  506. }
  507. /**
  508. * moves a question up in the list
  509. *
  510. * @author - Olivier Brouckaert
  511. * @author - Julio Montoya (rewrote the code)
  512. * @param - integer $id - question ID to move up
  513. */
  514. function moveUp($id)
  515. {
  516. // there is a bug with some version of PHP with the key and prev functions
  517. // the script commented was tested in dev.dokeos.com with no success
  518. // Instead of using prev and next this was change with arrays.
  519. /*
  520. foreach($this->questionList as $position=>$questionId)
  521. {
  522. // if question ID found
  523. if($questionId == $id)
  524. {
  525. // position of question in the array
  526. echo $pos1=$position; //1
  527. echo "<br>";
  528. prev($this->questionList);
  529. prev($this->questionList);
  530. // position of previous question in the array
  531. $pos2=key($this->questionList);
  532. //if the cursor of the array hit the end
  533. // then we must reset the array to get the previous key
  534. if($pos2===null)
  535. {
  536. end($this->questionList);
  537. prev($this->questionList);
  538. $pos2=key($this->questionList);
  539. }
  540. // error, can't move question
  541. if(!$pos2)
  542. {
  543. //echo 'cant move!';
  544. $pos2=key($this->questionList);
  545. reset($this->questionList);
  546. }
  547. $id2=$this->questionList[$pos2];
  548. // exits foreach()
  549. break;
  550. }
  551. $i++;
  552. }
  553. */
  554. $question_list =array();
  555. foreach($this->questionList as $position=>$questionId)
  556. {
  557. $question_list[]= $questionId;
  558. }
  559. $len=count($question_list);
  560. $orderlist=array_keys($this->questionList);
  561. for($i=0;$i<$len;$i++)
  562. {
  563. $questionId = $question_list[$i];
  564. if($questionId == $id)
  565. {
  566. // position of question in the array
  567. $pos1=$orderlist[$i];
  568. $pos2=$orderlist[$i-1];
  569. if($pos2===null)
  570. {
  571. $pos2 = $orderlist[$len-1];
  572. }
  573. // error, can't move question
  574. if(!$pos2)
  575. {
  576. $pos2=$orderlist[0];
  577. $i=0;
  578. }
  579. break;
  580. }
  581. }
  582. // permutes questions in the array
  583. $temp=$this->questionList[$pos2];
  584. $this->questionList[$pos2]=$this->questionList[$pos1];
  585. $this->questionList[$pos1]=$temp;
  586. }
  587. /**
  588. * moves a question down in the list
  589. *
  590. * @author - Olivier Brouckaert
  591. * @param - integer $id - question ID to move down
  592. */
  593. function moveDown($id)
  594. {
  595. // there is a bug with some version of PHP with the key and prev functions
  596. // the script commented was tested in dev.dokeos.com with no success
  597. // Instead of using prev and next this was change with arrays.
  598. /*
  599. foreach($this->questionList as $position=>$questionId)
  600. {
  601. // if question ID found
  602. if($questionId == $id)
  603. {
  604. // position of question in the array
  605. $pos1=$position;
  606. //next($this->questionList);
  607. // position of next question in the array
  608. $pos2=key($this->questionList);
  609. // error, can't move question
  610. if(!$pos2)
  611. {
  612. //echo 'cant move!';
  613. return;
  614. }
  615. $id2=$this->questionList[$pos2];
  616. // exits foreach()
  617. break;
  618. }
  619. }
  620. */
  621. $question_list =array();
  622. foreach($this->questionList as $position=>$questionId)
  623. {
  624. $question_list[]= $questionId;
  625. }
  626. $len=count($question_list);
  627. $orderlist=array_keys($this->questionList);
  628. for($i=0;$i<$len;$i++)
  629. {
  630. $questionId = $question_list[$i];
  631. if($questionId == $id)
  632. {
  633. $pos1=$orderlist[$i+1];
  634. $pos2 =$orderlist[$i];
  635. if(!$pos2)
  636. {
  637. //echo 'cant move!';
  638. }
  639. break;
  640. }
  641. }
  642. // permutes questions in the array
  643. $temp=$this->questionList[$pos2];
  644. $this->questionList[$pos2]=$this->questionList[$pos1];
  645. $this->questionList[$pos1]=$temp;
  646. }
  647. /**
  648. * adds a question into the question list
  649. *
  650. * @author - Olivier Brouckaert
  651. * @param - integer $questionId - question ID
  652. * @return - boolean - true if the question has been added, otherwise false
  653. */
  654. function addToList($questionId)
  655. {
  656. // checks if the question ID is not in the list
  657. if(!$this->isInList($questionId))
  658. {
  659. // selects the max position
  660. if(!$this->selectNbrQuestions())
  661. {
  662. $pos=1;
  663. }
  664. else
  665. {
  666. $pos=max(array_keys($this->questionList))+1;
  667. }
  668. $this->questionList[$pos]=$questionId;
  669. return true;
  670. }
  671. return false;
  672. }
  673. /**
  674. * removes a question from the question list
  675. *
  676. * @author - Olivier Brouckaert
  677. * @param - integer $questionId - question ID
  678. * @return - boolean - true if the question has been removed, otherwise false
  679. */
  680. function removeFromList($questionId)
  681. {
  682. // searches the position of the question ID in the list
  683. $pos=array_search($questionId,$this->questionList);
  684. // question not found
  685. if($pos === false)
  686. {
  687. return false;
  688. }
  689. else
  690. {
  691. // deletes the position from the array containing the wanted question ID
  692. unset($this->questionList[$pos]);
  693. return true;
  694. }
  695. }
  696. /**
  697. * deletes the exercise from the database
  698. * Notice : leaves the question in the data base
  699. *
  700. * @author - Olivier Brouckaert
  701. */
  702. function delete(){
  703. global $_course,$_user;
  704. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  705. $sql="UPDATE $TBL_EXERCICES SET active='-1' WHERE id='".Database::escape_string($this->id)."'";
  706. api_sql_query($sql);
  707. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizDeleted',$_user['user_id']);
  708. if (api_get_setting('search_enabled')=='true') {
  709. $this -> search_engine_delete();
  710. }
  711. }
  712. /**
  713. * Creates the form to create / edit an exercise
  714. * @param FormValidator $form the formvalidator instance (by reference)
  715. */
  716. function createForm ($form, $type='full')
  717. {
  718. global $id;
  719. if(empty($type)){
  720. $type='full';
  721. }
  722. // title
  723. $form -> addElement('text', 'exerciseTitle', get_lang('ExerciseName'),'class="input_titles"');
  724. // fck editor
  725. global $fck_attribute;
  726. $fck_attribute = array();
  727. $fck_attribute['Height'] = '200px';
  728. $fck_attribute['Width'] = '50%';
  729. $fck_attribute['ToolbarSet'] = 'NewTest';
  730. $fck_attribute['Config']['InDocument'] = false;
  731. $fck_attribute['Config']['CreateDocumentDir'] = '../../courses/'.api_get_course_path().'/document/';
  732. //$fck_attribute['Config']['CreateDocumentWebDir'] = api_get_path('WEB_COURSE_PATH').$_course['path'].'/document/';
  733. $form -> addElement ('html_editor', 'exerciseDescription', get_lang('ExerciseDescription'));
  734. if($type=='full') {
  735. // feedback type
  736. $feedback_option[0]=get_lang('Feedback');
  737. $feedback_option[1]=get_lang('DirectFeedback');
  738. $feedback_option[2]=get_lang('NoFeedback');
  739. $form -> addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  740. // test type
  741. $radios = array();
  742. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SimpleExercise'),'1');
  743. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2');
  744. $form -> addGroup($radios, null, get_lang('ExerciseType'), '<br />');
  745. $form -> addElement('html','<div class="row">
  746. <div class="label">&nbsp;</div>
  747. <div class="formw">
  748. <a href="javascript://" onclick=" return advanced_parameters()"><span id="img_plus_and_minus"><img src="../img/nolines_plus.gif" alt="" />'.get_lang('AdvancedParameters').'</span></a>
  749. </div>
  750. </div>');
  751. // Random questions
  752. $form -> addElement('html','<div id="options" style="display:none">');
  753. $random = array();
  754. $option=array();
  755. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10 ;
  756. $option = range(0,$max);
  757. $option[0]=get_lang('DoNotRandomize');
  758. $random[] = FormValidator :: createElement ('select', 'randomQuestions',null,$option);
  759. $random[] = FormValidator :: createElement ('static', 'help','help','<span style="font-style: italic;">'.get_lang('RandomQuestionsHelp').'</span>');
  760. //$random[] = FormValidator :: createElement ('text', 'randomQuestions', null,null,'0');
  761. $form -> addGroup($random,null,get_lang('RandomQuestions'),'<br />');
  762. $attempt_option=range(0,10);
  763. $attempt_option[0]=get_lang('Infinite');
  764. $form -> addElement('select', 'exerciseAttempts',get_lang('ExerciseAttempts'),$attempt_option);
  765. $form -> addElement('html','</div>');
  766. $form -> addElement('checkbox', 'enabletimelimit',get_lang('EnableTimeLimits'),null,'onclick = " return timelimit() "');
  767. $var= Exercise::selectTimeLimit();
  768. if(($this -> start_time!='0000-00-00 00:00:00')||($this -> end_time!='0000-00-00 00:00:00'))
  769. $form -> addElement('html','<div id="options2" style="display:block;">');
  770. else
  771. $form -> addElement('html','<div id="options2" style="display:none;">');
  772. //$form -> addElement('date', 'start_time', get_lang('ExeStartTime'), array('language'=>'es','format' => 'dMYHi'));
  773. //$form -> addElement('date', 'end_time', get_lang('ExeEndTime'), array('language'=>'es','format' => 'dMYHi'));
  774. $form->addElement('datepicker', 'start_time', get_lang('ExeStartTime'), array('form_name'=>'exercise_admin'));
  775. $form->addElement('datepicker', 'end_time', get_lang('ExeEndTime'), array('form_name'=>'exercise_admin'));
  776. //$form -> addElement('text', 'exerciseAttempts', get_lang('ExerciseAttempts').' : ',array('size'=>'2'));
  777. $form -> addElement('html','</div>');
  778. $defaults = array();
  779. if (api_get_setting('search_enabled') === 'true') {
  780. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  781. $form -> addElement ('checkbox', 'index_document','', get_lang('SearchFeatureDoIndexDocument'));
  782. $form -> addElement ('html','<br /><div class="row">');
  783. $form -> addElement ('html', '<div class="label">'. get_lang('SearchFeatureDocumentLanguage') .'</div>');
  784. $form -> addElement ('html', '<div class="formw">'. api_get_languages_combo() .'</div>');
  785. $form -> addElement ('html','</div><div class="sub-form">');
  786. $specific_fields = get_specific_field_list();
  787. foreach ($specific_fields as $specific_field) {
  788. $form -> addElement ('text', $specific_field['code'], $specific_field['name']);
  789. $filter = array('course_code'=> "'". api_get_course_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $this->id, 'tool_id' => '\''. TOOL_QUIZ .'\'');
  790. $values = get_specific_field_values_list($filter, array('value'));
  791. if ( !empty($values) ) {
  792. $arr_str_values = array();
  793. foreach ($values as $value) {
  794. $arr_str_values[] = $value['value'];
  795. }
  796. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  797. }
  798. }
  799. $form -> addElement ('html','</div>');
  800. }
  801. }
  802. // submit
  803. $form -> addElement('style_submit_button', 'submitExercise', get_lang('CreateModif'), 'class="save"');
  804. $form -> addRule ('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  805. if($type=='full') {
  806. // rules
  807. $form -> addRule ('exerciseAttempts', get_lang('Numeric'), 'numeric');
  808. $form -> addRule ('start_time', get_lang('InvalidDate'), 'date');
  809. $form -> addRule ('end_time', get_lang('InvalidDate'), 'date');
  810. $form -> addRule(array ('start_time', 'end_time'), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
  811. }
  812. // defaults
  813. if($type=='full') {
  814. if($this -> id > 0) {
  815. if ($this -> random > $this->selectNbrQuestions()) {
  816. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  817. } else {
  818. $defaults['randomQuestions'] = $this -> random;
  819. }
  820. $defaults['exerciseType'] = $this -> selectType();
  821. $defaults['exerciseTitle'] = $this -> selectTitle();
  822. $defaults['exerciseDescription'] = $this -> selectDescription();
  823. $defaults['exerciseAttempts'] = $this->selectAttempts();
  824. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  825. if(($this -> start_time!='0000-00-00 00:00:00')||($this -> end_time!='0000-00-00 00:00:00'))
  826. $defaults['enabletimelimit'] = 1;
  827. $defaults['start_time'] = ($this->start_time!='0000-00-00 00:00:00')? $this -> start_time : date('Y-m-d 12:00:00');
  828. $defaults['end_time'] = ($this->end_time!='0000-00-00 00:00:00')?$this -> end_time : date('Y-m-d 12:00:00');
  829. } else {
  830. $defaults['exerciseType'] = 1;
  831. $defaults['exerciseAttempts'] = 0;
  832. $defaults['randomQuestions'] = 0;
  833. $defaults['exerciseDescription'] = '';
  834. $defaults['exerciseFeedbackType'] = 0;
  835. $defaults['start_time'] = date('Y-m-d 12:00:00');
  836. $defaults['end_time'] = date('Y-m-d 12:00:00');
  837. }
  838. } else {
  839. $defaults['exerciseTitle'] = $this -> selectTitle();
  840. $defaults['exerciseDescription'] = $this -> selectDescription();
  841. }
  842. if (api_get_setting('search_enabled') === 'true') {
  843. $defaults['index_document'] = 'checked="checked"';
  844. }
  845. $form -> setDefaults($defaults);
  846. }
  847. /**
  848. * function which process the creation of exercises
  849. * @param FormValidator $form the formvalidator instance
  850. */
  851. function processCreation($form)
  852. {
  853. $this -> updateAttempts($form -> getSubmitValue('exerciseAttempts'));
  854. $this -> updateFeedbackType($form -> getSubmitValue('exerciseFeedbackType'));
  855. $this -> updateTitle($form -> getSubmitValue('exerciseTitle'));
  856. $this -> updateDescription($form -> getSubmitValue('exerciseDescription'));
  857. $this -> updateType($form -> getSubmitValue('exerciseType'));
  858. $this -> setRandom($form -> getSubmitValue('randomQuestions'));
  859. if($form -> getSubmitValue('enabletimelimit')==1)
  860. {
  861. $start_time = $form -> getSubmitValue('start_time');
  862. $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
  863. $end_time = $form -> getSubmitValue('end_time');
  864. $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
  865. }
  866. else
  867. {
  868. $this->start_time = '0000-00-00 00:00:00';
  869. $this->end_time = '0000-00-00 00:00:00';
  870. }
  871. //echo $end_time;exit;
  872. $this -> save();
  873. }
  874. function search_engine_save() {
  875. if ($_POST['index_document'] != 1) {
  876. return;
  877. }
  878. $course_id = api_get_course_id();
  879. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  880. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  881. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  882. $specific_fields = get_specific_field_list();
  883. $ic_slide = new IndexableChunk();
  884. $all_specific_terms = '';
  885. foreach ($specific_fields as $specific_field) {
  886. if (isset($_REQUEST[$specific_field['code']])) {
  887. $sterms = trim($_REQUEST[$specific_field['code']]);
  888. if (!empty($sterms)) {
  889. $all_specific_terms .= ' '. $sterms;
  890. $sterms = explode(',', $sterms);
  891. foreach ($sterms as $sterm) {
  892. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  893. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  894. }
  895. }
  896. }
  897. }
  898. // build the chunk to index
  899. $ic_slide->addValue("title", $this->exercise);
  900. $ic_slide->addCourseId($course_id);
  901. $ic_slide->addToolId(TOOL_QUIZ);
  902. $xapian_data = array(
  903. SE_COURSE_ID => $course_id,
  904. SE_TOOL_ID => TOOL_QUIZ,
  905. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  906. SE_USER => (int)api_get_user_id(),
  907. );
  908. $ic_slide->xapian_data = serialize($xapian_data);
  909. $exercise_description = $all_specific_terms .' '. $this->description;
  910. $ic_slide->addValue("content", $exercise_description);
  911. $di = new DokeosIndexer();
  912. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  913. $di->connectDb(NULL, NULL, $lang);
  914. $di->addChunk($ic_slide);
  915. //index and return search engine document id
  916. $did = $di->index();
  917. if ($did) {
  918. // save it to db
  919. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  920. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  921. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  922. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  923. api_sql_query($sql,__FILE__,__LINE__);
  924. }
  925. }
  926. function search_engine_edit() {
  927. // update search enchine and its values table if enabled
  928. if (api_get_setting('search_enabled')=='true') {
  929. $course_id = api_get_course_id();
  930. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  931. // get search_did
  932. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  933. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  934. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  935. $res = api_sql_query($sql, __FILE__, __LINE__);
  936. if (Database::num_rows($res) > 0) {
  937. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  938. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  939. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  940. $se_ref = Database::fetch_array($res);
  941. $specific_fields = get_specific_field_list();
  942. $ic_slide = new IndexableChunk();
  943. $all_specific_terms = '';
  944. foreach ($specific_fields as $specific_field) {
  945. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  946. if (isset($_REQUEST[$specific_field['code']])) {
  947. $sterms = trim($_REQUEST[$specific_field['code']]);
  948. $all_specific_terms .= ' '. $sterms;
  949. $sterms = explode(',', $sterms);
  950. foreach ($sterms as $sterm) {
  951. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  952. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  953. }
  954. }
  955. }
  956. // build the chunk to index
  957. $ic_slide->addValue("title", $this->exercise);
  958. $ic_slide->addCourseId($course_id);
  959. $ic_slide->addToolId(TOOL_QUIZ);
  960. $xapian_data = array(
  961. SE_COURSE_ID => $course_id,
  962. SE_TOOL_ID => TOOL_QUIZ,
  963. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  964. SE_USER => (int)api_get_user_id(),
  965. );
  966. $ic_slide->xapian_data = serialize($xapian_data);
  967. $exercise_description = $all_specific_terms .' '. $this->description;
  968. $ic_slide->addValue("content", $exercise_description);
  969. $di = new DokeosIndexer();
  970. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  971. $di->connectDb(NULL, NULL, $lang);
  972. $di->remove_document((int)$se_ref['search_did']);
  973. $di->addChunk($ic_slide);
  974. //index and return search engine document id
  975. $did = $di->index();
  976. if ($did) {
  977. // save it to db
  978. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  979. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  980. api_sql_query($sql,__FILE__,__LINE__);
  981. //var_dump($sql);
  982. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  983. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  984. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  985. api_sql_query($sql,__FILE__,__LINE__);
  986. }
  987. }
  988. }
  989. }
  990. function search_engine_delete() {
  991. // remove from search engine if enabled
  992. if (api_get_setting('search_enabled') == 'true') {
  993. $course_id = api_get_course_id();
  994. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  995. $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';
  996. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  997. $res = api_sql_query($sql, __FILE__, __LINE__);
  998. if (Database::num_rows($res) > 0) {
  999. $row = Database::fetch_array($res);
  1000. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  1001. $di = new DokeosIndexer();
  1002. $di->remove_document((int)$row['search_did']);
  1003. unset($di);
  1004. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1005. foreach ( $this->questionList as $question_i) {
  1006. $sql = 'SELECT type FROM %s WHERE id=%s';
  1007. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  1008. $qres = api_sql_query($sql, __FILE__, __LINE__);
  1009. if (Database::num_rows($qres) > 0) {
  1010. $qrow = Database::fetch_array($qres);
  1011. $objQuestion = Question::getInstance($qrow['type']);
  1012. $objQuestion = Question::read((int)$question_i);
  1013. $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
  1014. unset($objQuestion);
  1015. }
  1016. }
  1017. }
  1018. $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';
  1019. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1020. api_sql_query($sql, __FILE__, __LINE__);
  1021. // remove terms from db
  1022. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  1023. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  1024. }
  1025. }
  1026. }
  1027. endif;
  1028. ?>