exercise.class.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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 18098 2009-01-30 23:12:27Z cvargas1 $
  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. $form -> addElement('html','<div id="options2" style="display:'.$state.'">');
  769. //$form -> addElement('date', 'start_time', get_lang('ExeStartTime'), array('language'=>'es','format' => 'dMYHi'));
  770. //$form -> addElement('date', 'end_time', get_lang('ExeEndTime'), array('language'=>'es','format' => 'dMYHi'));
  771. $form->addElement('datepicker', 'start_time', get_lang('ExeStartTime'), array('form_name'=>'exercise_admin'));
  772. $form->addElement('datepicker', 'end_time', get_lang('ExeEndTime'), array('form_name'=>'exercise_admin'));
  773. //$form -> addElement('text', 'exerciseAttempts', get_lang('ExerciseAttempts').' : ',array('size'=>'2'));
  774. $form -> addElement('html','</div>');
  775. $defaults = array();
  776. if (api_get_setting('search_enabled') === 'true') {
  777. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  778. $form -> addElement ('checkbox', 'index_document','', get_lang('SearchFeatureDoIndexDocument'));
  779. $form -> addElement ('html','<br /><div class="row">');
  780. $form -> addElement ('html', '<div class="label">'. get_lang('SearchFeatureDocumentLanguage') .'</div>');
  781. $form -> addElement ('html', '<div class="formw">'. api_get_languages_combo() .'</div>');
  782. $form -> addElement ('html','</div><div class="sub-form">');
  783. $specific_fields = get_specific_field_list();
  784. foreach ($specific_fields as $specific_field) {
  785. $form -> addElement ('text', $specific_field['code'], $specific_field['name']);
  786. $filter = array('course_code'=> "'". api_get_course_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $this->id, 'tool_id' => '\''. TOOL_QUIZ .'\'');
  787. $values = get_specific_field_values_list($filter, array('value'));
  788. if ( !empty($values) ) {
  789. $arr_str_values = array();
  790. foreach ($values as $value) {
  791. $arr_str_values[] = $value['value'];
  792. }
  793. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  794. }
  795. }
  796. $form -> addElement ('html','</div>');
  797. }
  798. }
  799. // submit
  800. $form -> addElement('submit', 'submitExercise', get_lang('Ok'));
  801. $form -> addRule ('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  802. if($type=='full') {
  803. // rules
  804. $form -> addRule ('exerciseAttempts', get_lang('Numeric'), 'numeric');
  805. $form -> addRule ('start_time', get_lang('InvalidDate'), 'date');
  806. $form -> addRule ('end_time', get_lang('InvalidDate'), 'date');
  807. $form -> addRule(array ('start_time', 'end_time'), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
  808. }
  809. // defaults
  810. if($type=='full') {
  811. if($this -> id > 0) {
  812. if ($this -> random > $this->selectNbrQuestions()) {
  813. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  814. } else {
  815. $defaults['randomQuestions'] = $this -> random;
  816. }
  817. $defaults['exerciseType'] = $this -> selectType();
  818. $defaults['exerciseTitle'] = $this -> selectTitle();
  819. $defaults['exerciseDescription'] = $this -> selectDescription();
  820. $defaults['exerciseAttempts'] = $this->selectAttempts();
  821. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  822. if(($this -> start_time!='0000-00-00 00:00:00')||($this -> end_time!='0000-00-00 00:00:00'))
  823. $defaults['enabletimelimit'] = 1;
  824. $defaults['start_time'] = ($this->start_time!='0000-00-00 00:00:00')? $this -> start_time : date('Y-m-d 12:00:00');
  825. $defaults['end_time'] = ($this->end_time!='0000-00-00 00:00:00')?$this -> end_time : date('Y-m-d 12:00:00');
  826. } else {
  827. $defaults['exerciseType'] = 1;
  828. $defaults['exerciseAttempts'] = 0;
  829. $defaults['randomQuestions'] = 0;
  830. $defaults['exerciseDescription'] = '';
  831. $defaults['exerciseFeedbackType'] = 0;
  832. $defaults['start_time'] = date('Y-m-d 12:00:00');
  833. $defaults['end_time'] = date('Y-m-d 12:00:00');
  834. }
  835. } else {
  836. $defaults['exerciseTitle'] = $this -> selectTitle();
  837. $defaults['exerciseDescription'] = $this -> selectDescription();
  838. }
  839. if (api_get_setting('search_enabled') === 'true') {
  840. $defaults['index_document'] = 'checked="checked"';
  841. }
  842. $form -> setDefaults($defaults);
  843. }
  844. /**
  845. * function which process the creation of exercises
  846. * @param FormValidator $form the formvalidator instance
  847. */
  848. function processCreation($form)
  849. {
  850. $this -> updateAttempts($form -> getSubmitValue('exerciseAttempts'));
  851. $this -> updateFeedbackType($form -> getSubmitValue('exerciseFeedbackType'));
  852. $this -> updateTitle($form -> getSubmitValue('exerciseTitle'));
  853. $this -> updateDescription($form -> getSubmitValue('exerciseDescription'));
  854. $this -> updateType($form -> getSubmitValue('exerciseType'));
  855. $this -> setRandom($form -> getSubmitValue('randomQuestions'));
  856. if($form -> getSubmitValue('enabletimelimit')==1)
  857. {
  858. $start_time = $form -> getSubmitValue('start_time');
  859. $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
  860. $end_time = $form -> getSubmitValue('end_time');
  861. $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
  862. }
  863. else
  864. {
  865. $this->start_time = '0000-00-00 00:00:00';
  866. $this->end_time = '0000-00-00 00:00:00';
  867. }
  868. //echo $end_time;exit;
  869. $this -> save();
  870. }
  871. function search_engine_save() {
  872. if ($_POST['index_document'] != 1) {
  873. return;
  874. }
  875. $course_id = api_get_course_id();
  876. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  877. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  878. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  879. $specific_fields = get_specific_field_list();
  880. $ic_slide = new IndexableChunk();
  881. $all_specific_terms = '';
  882. foreach ($specific_fields as $specific_field) {
  883. if (isset($_REQUEST[$specific_field['code']])) {
  884. $sterms = trim($_REQUEST[$specific_field['code']]);
  885. if (!empty($sterms)) {
  886. $all_specific_terms .= ' '. $sterms;
  887. $sterms = explode(',', $sterms);
  888. foreach ($sterms as $sterm) {
  889. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  890. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  891. }
  892. }
  893. }
  894. }
  895. // build the chunk to index
  896. $ic_slide->addValue("title", $this->exercise);
  897. $ic_slide->addCourseId($course_id);
  898. $ic_slide->addToolId(TOOL_QUIZ);
  899. $xapian_data = array(
  900. SE_COURSE_ID => $course_id,
  901. SE_TOOL_ID => TOOL_QUIZ,
  902. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  903. SE_USER => (int)api_get_user_id(),
  904. );
  905. $ic_slide->xapian_data = serialize($xapian_data);
  906. $exercise_description = $all_specific_terms .' '. $this->description;
  907. $ic_slide->addValue("content", $exercise_description);
  908. $di = new DokeosIndexer();
  909. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  910. $di->connectDb(NULL, NULL, $lang);
  911. $di->addChunk($ic_slide);
  912. //index and return search engine document id
  913. $did = $di->index();
  914. if ($did) {
  915. // save it to db
  916. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  917. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  918. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  919. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  920. api_sql_query($sql,__FILE__,__LINE__);
  921. }
  922. }
  923. function search_engine_edit() {
  924. // update search enchine and its values table if enabled
  925. if (api_get_setting('search_enabled')=='true') {
  926. $course_id = api_get_course_id();
  927. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  928. // get search_did
  929. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  930. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  931. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  932. $res = api_sql_query($sql, __FILE__, __LINE__);
  933. if (Database::num_rows($res) > 0) {
  934. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  935. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  936. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  937. $se_ref = Database::fetch_array($res);
  938. $specific_fields = get_specific_field_list();
  939. $ic_slide = new IndexableChunk();
  940. $all_specific_terms = '';
  941. foreach ($specific_fields as $specific_field) {
  942. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  943. if (isset($_REQUEST[$specific_field['code']])) {
  944. $sterms = trim($_REQUEST[$specific_field['code']]);
  945. $all_specific_terms .= ' '. $sterms;
  946. $sterms = explode(',', $sterms);
  947. foreach ($sterms as $sterm) {
  948. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  949. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  950. }
  951. }
  952. }
  953. // build the chunk to index
  954. $ic_slide->addValue("title", $this->exercise);
  955. $ic_slide->addCourseId($course_id);
  956. $ic_slide->addToolId(TOOL_QUIZ);
  957. $xapian_data = array(
  958. SE_COURSE_ID => $course_id,
  959. SE_TOOL_ID => TOOL_QUIZ,
  960. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  961. SE_USER => (int)api_get_user_id(),
  962. );
  963. $ic_slide->xapian_data = serialize($xapian_data);
  964. $exercise_description = $all_specific_terms .' '. $this->description;
  965. $ic_slide->addValue("content", $exercise_description);
  966. $di = new DokeosIndexer();
  967. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  968. $di->connectDb(NULL, NULL, $lang);
  969. $di->remove_document((int)$se_ref['search_did']);
  970. $di->addChunk($ic_slide);
  971. //index and return search engine document id
  972. $did = $di->index();
  973. if ($did) {
  974. // save it to db
  975. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  976. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  977. api_sql_query($sql,__FILE__,__LINE__);
  978. //var_dump($sql);
  979. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  980. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  981. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  982. api_sql_query($sql,__FILE__,__LINE__);
  983. }
  984. }
  985. }
  986. }
  987. function search_engine_delete() {
  988. // remove from search engine if enabled
  989. if (api_get_setting('search_enabled') == 'true') {
  990. $course_id = api_get_course_id();
  991. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  992. $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';
  993. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  994. $res = api_sql_query($sql, __FILE__, __LINE__);
  995. if (Database::num_rows($res) > 0) {
  996. $row = Database::fetch_array($res);
  997. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  998. $di = new DokeosIndexer();
  999. $di->remove_document((int)$row['search_did']);
  1000. unset($di);
  1001. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1002. foreach ( $this->questionList as $question_i) {
  1003. $sql = 'SELECT type FROM %s WHERE id=%s';
  1004. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  1005. $qres = api_sql_query($sql, __FILE__, __LINE__);
  1006. if (Database::num_rows($qres) > 0) {
  1007. $qrow = Database::fetch_array($qres);
  1008. $objQuestion = Question::getInstance($qrow['type']);
  1009. $objQuestion = Question::read((int)$question_i);
  1010. $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
  1011. unset($objQuestion);
  1012. }
  1013. }
  1014. }
  1015. $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';
  1016. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1017. api_sql_query($sql, __FILE__, __LINE__);
  1018. // remove terms from db
  1019. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  1020. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  1021. }
  1022. }
  1023. }
  1024. endif;
  1025. ?>