exercise.class.php 37 KB

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