exercise.class.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Exercise class: This class allows to instantiate an object of type Exercise
  5. * @package dokeos.exercise
  6. * @author Olivier Brouckaert
  7. * @version $Id: exercise.class.php 22046 2009-07-14 01:45:19Z ivantcholakov $
  8. */
  9. define('ALL_ON_ONE_PAGE',1);
  10. define('ONE_PER_PAGE',2);
  11. define('EXERCISE_FEEDBACK_TYPE_END',0);
  12. define('EXERCISE_FEEDBACK_TYPE_DIRECT',1);
  13. define('EXERCISE_FEEDBACK_TYPE_EXAM',2);
  14. if(!class_exists('Exercise')):
  15. class Exercise
  16. {
  17. var $id;
  18. var $exercise;
  19. var $description;
  20. var $sound;
  21. var $type;
  22. var $random;
  23. var $random_answers;
  24. var $active;
  25. var $timeLimit;
  26. var $attempts;
  27. var $feedbacktype;
  28. var $end_time;
  29. var $start_time;
  30. var $questionList; // array with the list of this exercise's questions
  31. var $results_disabled;
  32. var $expired_time;
  33. /**
  34. * constructor of the class
  35. *
  36. * @author - Olivier Brouckaert
  37. */
  38. function Exercise()
  39. {
  40. $this->id=0;
  41. $this->exercise='';
  42. $this->description='';
  43. $this->sound='';
  44. $this->type=1;
  45. $this->random=0;
  46. $this->random_answers=0;
  47. $this->active=1;
  48. $this->questionList=array();
  49. $this->timeLimit = 0;
  50. $this->end_time = '0000-00-00 00:00:00';
  51. $this->start_time = '0000-00-00 00:00:00';
  52. $this->results_disabled =1;
  53. $this->expired_time = '0000-00-00 00:00:00';
  54. }
  55. /**
  56. * reads exercise informations from the data base
  57. *
  58. * @author - Olivier Brouckaert
  59. * @param - integer $id - exercise ID
  60. * @return - boolean - true if exercise exists, otherwise false
  61. */
  62. function read($id)
  63. {
  64. global $_course;
  65. global $_configuration;
  66. global $questionList;
  67. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  68. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  69. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  70. #$TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  71. $sql="SELECT title,description,sound,type,random, random_answers, active, results_disabled, max_attempt,start_time,end_time,feedback_type,expired_time FROM $TBL_EXERCICES WHERE id='".Database::escape_string($id)."'";
  72. $result=Database::query($sql);
  73. // if the exercise has been found
  74. if($object=Database::fetch_object($result))
  75. {
  76. $this->id=$id;
  77. $this->exercise=$object->title;
  78. $this->description=$object->description;
  79. $this->sound=$object->sound;
  80. $this->type=$object->type;
  81. $this->random=$object->random;
  82. $this->random_answers=$object->random_answers;
  83. $this->active=$object->active;
  84. $this->results_disabled =$object->results_disabled;
  85. $this->attempts = $object->max_attempt;
  86. $this->feedbacktype = $object->feedback_type;
  87. $this->end_time = $object->end_time;
  88. $this->start_time = $object->start_time;
  89. $this->expired_time = $object->expired_time;
  90. $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";
  91. $result=Database::query($sql);
  92. // fills the array with the question ID for this exercise
  93. // the key of the array is the question position
  94. while($object=Database::fetch_object($result))
  95. {
  96. // makes sure that the question position is unique
  97. while(isset($this->questionList[$object->question_order]))
  98. {
  99. $object->question_order++;
  100. }
  101. $this->questionList[$object->question_order]=$object->question_id;
  102. }
  103. //var_dump($this->end_time,$object->start_time);
  104. if($this->random > 0){
  105. $this->questionList = $this->selectRandomList();
  106. }
  107. //overload questions list with recorded questions list
  108. //load questions only for exercises of type 'one question per page'
  109. //this is needed only is there is no questions
  110. //
  111. if ($this->type == 2 && $_configuration['live_exercise_tracking'] && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED'))
  112. {
  113. //if(empty($_SESSION['questionList']))
  114. $this->questionList = $questionList;
  115. }
  116. return true;
  117. }
  118. // exercise not found
  119. return false;
  120. }
  121. /**
  122. * returns the exercise ID
  123. *
  124. * @author - Olivier Brouckaert
  125. * @return - integer - exercise ID
  126. */
  127. function selectId()
  128. {
  129. return $this->id;
  130. }
  131. /**
  132. * returns the exercise title
  133. *
  134. * @author - Olivier Brouckaert
  135. * @return - string - exercise title
  136. */
  137. function selectTitle()
  138. {
  139. return $this->exercise;
  140. }
  141. /**
  142. * returns the number of attempts setted
  143. *
  144. * @return - numeric - exercise attempts
  145. */
  146. function selectAttempts()
  147. {
  148. return $this->attempts;
  149. }
  150. /** returns the number of FeedbackType *
  151. * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  152. * @return - numeric - exercise attempts
  153. */
  154. function selectFeedbackType()
  155. {
  156. return $this->feedbacktype;
  157. }
  158. /**
  159. * returns the time limit
  160. */
  161. function selectTimeLimit()
  162. {
  163. return $this->timeLimit;
  164. }
  165. /**
  166. * returns the exercise description
  167. *
  168. * @author - Olivier Brouckaert
  169. * @return - string - exercise description
  170. */
  171. function selectDescription()
  172. {
  173. return $this->description;
  174. }
  175. /**
  176. * returns the exercise sound file
  177. *
  178. * @author - Olivier Brouckaert
  179. * @return - string - exercise description
  180. */
  181. function selectSound()
  182. {
  183. return $this->sound;
  184. }
  185. /**
  186. * returns the exercise type
  187. *
  188. * @author - Olivier Brouckaert
  189. * @return - integer - exercise type
  190. */
  191. function selectType()
  192. {
  193. return $this->type;
  194. }
  195. /**
  196. * tells if questions are selected randomly, and if so returns the draws
  197. *
  198. * @author - Carlos Vargas
  199. * @return - integer - results disabled exercise
  200. */
  201. function selectResultsDisabled()
  202. {
  203. return $this->results_disabled;
  204. }
  205. /**
  206. * tells if questions are selected randomly, and if so returns the draws
  207. *
  208. * @author - Olivier Brouckaert
  209. * @return - integer - 0 if not random, otherwise the draws
  210. */
  211. function isRandom()
  212. {
  213. if($this->random > 0){
  214. return true;
  215. }
  216. else{
  217. return false;
  218. }
  219. }
  220. /**
  221. * returns random answers status.
  222. *
  223. * @author - Juan Carlos Ra�a
  224. */
  225. function selectRandomAnswers()
  226. {
  227. $this->random_answers;
  228. return $this->random_answers;
  229. }
  230. /**
  231. * Same as isRandom() but has a name applied to values different than 0 or 1
  232. */
  233. function getShuffle()
  234. {
  235. return $this->random;
  236. }
  237. /**
  238. * returns the exercise status (1 = enabled ; 0 = disabled)
  239. *
  240. * @author - Olivier Brouckaert
  241. * @return - boolean - true if enabled, otherwise false
  242. */
  243. function selectStatus()
  244. {
  245. return $this->active;
  246. }
  247. /**
  248. * returns the array with the question ID list
  249. *
  250. * @author - Olivier Brouckaert
  251. * @return - array - question ID list
  252. */
  253. function selectQuestionList()
  254. {
  255. return $this->questionList;
  256. }
  257. /**
  258. * returns the number of questions in this exercise
  259. *
  260. * @author - Olivier Brouckaert
  261. * @return - integer - number of questions
  262. */
  263. function selectNbrQuestions()
  264. {
  265. return sizeof($this->questionList);
  266. }
  267. /**
  268. * selects questions randomly in the question list
  269. *
  270. * @author - Olivier Brouckaert
  271. * @return - array - if the exercise is not set to take questions randomly, returns the question list
  272. * without randomizing, otherwise, returns the list with questions selected randomly
  273. */
  274. function selectRandomList()
  275. {
  276. $nbQuestions = $this->selectNbrQuestions();
  277. $temp_list = $this->questionList;
  278. //error_log(print_r($temp_list,true));
  279. //error_log(count($temp_list));
  280. if (count($temp_list)<>0) {
  281. shuffle($temp_list);
  282. return array_combine(range(1,$nbQuestions),$temp_list);
  283. }
  284. $nbQuestions = $this->selectNbrQuestions();
  285. //Not a random exercise, or if there are not at least 2 questions
  286. if($this->random == 0 || $nbQuestions < 2)
  287. {
  288. return $this->questionList;
  289. }
  290. $randQuestionList = array();
  291. $alreadyChosen = array();
  292. for($i=0; $i < $this->random; $i++)
  293. {
  294. if($i < $nbQuestions){
  295. do
  296. {
  297. $rand=rand(1,$nbQuestions);
  298. }
  299. while(in_array($rand,$alreadyChosen));
  300. $alreadyChosen[]=$rand;
  301. $randQuestionList[$rand] = $this->questionList[$rand];
  302. }
  303. }
  304. return $randQuestionList;
  305. }
  306. /**
  307. * returns 'true' if the question ID is in the question list
  308. *
  309. * @author - Olivier Brouckaert
  310. * @param - integer $questionId - question ID
  311. * @return - boolean - true if in the list, otherwise false
  312. */
  313. function isInList($questionId)
  314. {
  315. if (is_array($this->questionList))
  316. return in_array($questionId,$this->questionList);
  317. else
  318. return false;
  319. }
  320. /**
  321. * changes the exercise title
  322. *
  323. * @author - Olivier Brouckaert
  324. * @param - string $title - exercise title
  325. */
  326. function updateTitle($title)
  327. {
  328. $this->exercise=$title;
  329. }
  330. /**
  331. * changes the exercise max attempts
  332. *
  333. * @param - numeric $attempts - exercise max attempts
  334. */
  335. function updateAttempts($attempts)
  336. {
  337. $this->attempts=$attempts;
  338. }
  339. /**
  340. * changes the exercise feedback type
  341. *
  342. * @param - numeric $attempts - exercise max attempts
  343. */
  344. function updateFeedbackType($feedback_type)
  345. {
  346. $this->feedbacktype=$feedback_type;
  347. }
  348. /**
  349. * changes the exercise description
  350. *
  351. * @author - Olivier Brouckaert
  352. * @param - string $description - exercise description
  353. */
  354. function updateDescription($description)
  355. {
  356. $this->description=$description;
  357. }
  358. /**
  359. * changes the exercise expired_time
  360. *
  361. * @author - Isaac flores
  362. * @param - int The expired time of the quiz
  363. */
  364. function updateExpiredTime($expired_time)
  365. {
  366. $this->expired_time = $expired_time;
  367. }
  368. /**
  369. * changes the exercise sound file
  370. *
  371. * @author - Olivier Brouckaert
  372. * @param - string $sound - exercise sound file
  373. * @param - string $delete - ask to delete the file
  374. */
  375. function updateSound($sound,$delete)
  376. {
  377. global $audioPath, $documentPath,$_course, $_user;
  378. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  379. $TBL_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  380. if($sound['size'] && (strstr($sound['type'],'audio') || strstr($sound['type'],'video')))
  381. {
  382. $this->sound=$sound['name'];
  383. if(@move_uploaded_file($sound['tmp_name'],$audioPath.'/'.$this->sound))
  384. {
  385. $query="SELECT 1 FROM $TBL_DOCUMENT "
  386. ." WHERE path='".str_replace($documentPath,'',$audioPath).'/'.$this->sound."'";
  387. $result=Database::query($query);
  388. if(!Database::num_rows($result))
  389. {
  390. /*$query="INSERT INTO $TBL_DOCUMENT(path,filetype) VALUES "
  391. ." ('".str_replace($documentPath,'',$audioPath).'/'.$this->sound."','file')";
  392. Database::query($query);*/
  393. $id = add_document($_course,str_replace($documentPath,'',$audioPath).'/'.$this->sound,'file',$sound['size'],$sound['name']);
  394. //$id = Database::insert_id();
  395. //$time = time();
  396. //$time = date("Y-m-d H:i:s", $time);
  397. // insert into the item_property table, using default visibility of "visible"
  398. /*$query = "INSERT INTO $TBL_ITEM_PROPERTY "
  399. ."(tool, ref, insert_user_id,to_group_id, insert_date, lastedit_date, lastedit_type) "
  400. ." VALUES "
  401. ."('".TOOL_DOCUMENT."', $id, $_user['user_id'], 0, '$time', '$time', 'DocumentAdded' )";
  402. Database::query($query);*/
  403. api_item_property_update($_course, TOOL_DOCUMENT, $id, 'DocumentAdded',$_user['user_id']);
  404. item_property_update_on_folder($_course,str_replace($documentPath,'',$audioPath),$_user['user_id']);
  405. }
  406. }
  407. }
  408. elseif($delete && is_file($audioPath.'/'.$this->sound))
  409. {
  410. $this->sound='';
  411. }
  412. }
  413. /**
  414. * changes the exercise type
  415. *
  416. * @author - Olivier Brouckaert
  417. * @param - integer $type - exercise type
  418. */
  419. function updateType($type)
  420. {
  421. $this->type=$type;
  422. }
  423. /**
  424. * sets to 0 if questions are not selected randomly
  425. * if questions are selected randomly, sets the draws
  426. *
  427. * @author - Olivier Brouckaert
  428. * @param - integer $random - 0 if not random, otherwise the draws
  429. */
  430. function setRandom($random)
  431. {
  432. $this->random=$random;
  433. }
  434. /**
  435. * sets to 0 if answers are not selected randomly
  436. * if answers are selected randomly
  437. * @author - Juan Carlos Ra�a
  438. * @param - integer $random_answers - random answers
  439. */
  440. function updateRandomAnswers($random_answers)
  441. {
  442. $this->$random_answers = $random_answers;
  443. }
  444. /**
  445. * enables the exercise
  446. *
  447. * @author - Olivier Brouckaert
  448. */
  449. function enable()
  450. {
  451. $this->active=1;
  452. }
  453. /**
  454. * disables the exercise
  455. *
  456. * @author - Olivier Brouckaert
  457. */
  458. function disable()
  459. {
  460. $this->active=0;
  461. }
  462. function disable_results()
  463. {
  464. $this->results_disabled = true;
  465. }
  466. function enable_results()
  467. {
  468. $this->results_disabled = false;
  469. }
  470. function updateResultsDisabled($results_disabled)
  471. {
  472. if ($results_disabled==1){
  473. $this->results_disabled = true;
  474. } else {
  475. $this->results_disabled = false;
  476. }
  477. }
  478. /**
  479. * updates the exercise in the data base
  480. *
  481. * @author - Olivier Brouckaert
  482. */
  483. function save($type_e='')
  484. {
  485. global $_course,$_user;
  486. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  487. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  488. $TBL_QUIZ_QUESTION= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  489. $id = $this->id;
  490. $exercise = $this->exercise;
  491. $description = $this->description;
  492. $sound = $this->sound;
  493. $type = $this->type;
  494. $attempts = $this->attempts;
  495. $feedbacktype = $this->feedbacktype;
  496. $random = $this->random;
  497. $random_answers = $this->random_answers;
  498. $active = $this->active;
  499. $session_id = api_get_session_id();
  500. $expired_time = $this->expired_time;
  501. if ($feedbacktype==1){
  502. $results_disabled = 1;
  503. } else {
  504. $results_disabled = intval($this->results_disabled);
  505. }
  506. $start_time = Database::escape_string($this->start_time);
  507. $end_time = Database::escape_string($this->end_time);
  508. // exercise already exists
  509. if($id) {
  510. $sql="UPDATE $TBL_EXERCICES SET
  511. title='".Database::escape_string($exercise)."',
  512. description='".Database::escape_string($description)."'";
  513. if ($type_e != 'simple') {
  514. $sql .= ", sound='".Database::escape_string($sound)."',
  515. type='".Database::escape_string($type)."',
  516. random='".Database::escape_string($random)."',
  517. random_answers='".Database::escape_string($random_answers)."',
  518. active='".Database::escape_string($active)."',
  519. feedback_type='".Database::escape_string($feedbacktype)."',
  520. start_time='$start_time',end_time='$end_time',
  521. max_attempt='".Database::escape_string($attempts)."',
  522. expired_time='".Database::escape_string($expired_time)."',
  523. results_disabled='".Database::escape_string($results_disabled)."'";
  524. }
  525. $sql .= " WHERE id='".Database::escape_string($id)."'";
  526. // echo $sql;
  527. Database::query($sql);
  528. // update into the item_property table
  529. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizUpdated',$_user['user_id']);
  530. if (api_get_setting('search_enabled')=='true') {
  531. $this -> search_engine_edit();
  532. }
  533. } else {// creates a new exercise
  534. //add condition by anonymous user
  535. /*if (!api_is_anonymous()) {
  536. //is course manager
  537. $cond1=Database::escape_string($exercise);
  538. $cond2=Database::escape_string($description);
  539. } else {
  540. //is anonymous user
  541. $cond1=Database::escape_string(Security::remove_XSS($exercise));
  542. $cond2=Database::escape_string(Security::remove_XSS(api_html_entity_decode($description),COURSEMANAGERLOWSECURITY));
  543. }*/
  544. $sql="INSERT INTO $TBL_EXERCICES (start_time, end_time, title, description, sound, type, random, random_answers,active, results_disabled, max_attempt, feedback_type, expired_time, session_id)
  545. VALUES(
  546. '$start_time','$end_time',
  547. '".Database::escape_string($exercise)."',
  548. '".Database::escape_string($description)."',
  549. '".Database::escape_string($sound)."',
  550. '".Database::escape_string($type)."',
  551. '".Database::escape_string($random)."',
  552. '".Database::escape_string($random_answers)."',
  553. '".Database::escape_string($active)."',
  554. '".Database::escape_string($results_disabled)."',
  555. '".Database::escape_string($attempts)."',
  556. '".Database::escape_string($feedbacktype)."',
  557. '".Database::escape_string($expired_time)."',
  558. '".Database::escape_string($session_id)."'
  559. )";
  560. Database::query($sql);
  561. $this->id=Database::insert_id();
  562. // insert into the item_property table
  563. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizAdded',$_user['user_id']);
  564. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  565. $this -> search_engine_save();
  566. }
  567. }
  568. // updates the question position
  569. $this->update_question_positions();
  570. }
  571. function update_question_positions() {
  572. // updates the question position
  573. $TBL_QUIZ_QUESTION= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  574. foreach($this->questionList as $position=>$questionId)
  575. {
  576. //$sql="UPDATE $TBL_QUESTIONS SET position='".Database::escape_string($position)."' WHERE id='".Database::escape_string($questionId)."'";
  577. $sql="UPDATE $TBL_QUIZ_QUESTION SET question_order='".Database::escape_string($position)."' " .
  578. "WHERE question_id='".Database::escape_string($questionId)."' and exercice_id=".Database::escape_string($this->id)."";
  579. Database::query($sql);
  580. }
  581. }
  582. /**
  583. * moves a question up in the list
  584. *
  585. * @author - Olivier Brouckaert
  586. * @author - Julio Montoya (rewrote the code)
  587. * @param - integer $id - question ID to move up
  588. */
  589. function moveUp($id)
  590. {
  591. // there is a bug with some version of PHP with the key and prev functions
  592. // the script commented was tested in dev.dokeos.com with no success
  593. // Instead of using prev and next this was change with arrays.
  594. /*
  595. foreach($this->questionList as $position=>$questionId)
  596. {
  597. // if question ID found
  598. if($questionId == $id)
  599. {
  600. // position of question in the array
  601. echo $pos1=$position; //1
  602. echo "<br>";
  603. prev($this->questionList);
  604. prev($this->questionList);
  605. // position of previous question in the array
  606. $pos2=key($this->questionList);
  607. //if the cursor of the array hit the end
  608. // then we must reset the array to get the previous key
  609. if($pos2===null)
  610. {
  611. end($this->questionList);
  612. prev($this->questionList);
  613. $pos2=key($this->questionList);
  614. }
  615. // error, can't move question
  616. if(!$pos2)
  617. {
  618. //echo 'cant move!';
  619. $pos2=key($this->questionList);
  620. reset($this->questionList);
  621. }
  622. $id2=$this->questionList[$pos2];
  623. // exits foreach()
  624. break;
  625. }
  626. $i++;
  627. }
  628. */
  629. $question_list =array();
  630. foreach($this->questionList as $position=>$questionId)
  631. {
  632. $question_list[]= $questionId;
  633. }
  634. $len=count($question_list);
  635. $orderlist=array_keys($this->questionList);
  636. for($i=0;$i<$len;$i++)
  637. {
  638. $questionId = $question_list[$i];
  639. if($questionId == $id)
  640. {
  641. // position of question in the array
  642. $pos1=$orderlist[$i];
  643. $pos2=$orderlist[$i-1];
  644. if($pos2===null)
  645. {
  646. $pos2 = $orderlist[$len-1];
  647. }
  648. // error, can't move question
  649. if(!$pos2)
  650. {
  651. $pos2=$orderlist[0];
  652. $i=0;
  653. }
  654. break;
  655. }
  656. }
  657. // permutes questions in the array
  658. $temp=$this->questionList[$pos2];
  659. $this->questionList[$pos2]=$this->questionList[$pos1];
  660. $this->questionList[$pos1]=$temp;
  661. }
  662. /**
  663. * moves a question down in the list
  664. *
  665. * @author - Olivier Brouckaert
  666. * @param - integer $id - question ID to move down
  667. */
  668. function moveDown($id)
  669. {
  670. // there is a bug with some version of PHP with the key and prev functions
  671. // the script commented was tested in dev.dokeos.com with no success
  672. // Instead of using prev and next this was change with arrays.
  673. /*
  674. foreach($this->questionList as $position=>$questionId)
  675. {
  676. // if question ID found
  677. if($questionId == $id)
  678. {
  679. // position of question in the array
  680. $pos1=$position;
  681. //next($this->questionList);
  682. // position of next question in the array
  683. $pos2=key($this->questionList);
  684. // error, can't move question
  685. if(!$pos2)
  686. {
  687. //echo 'cant move!';
  688. return;
  689. }
  690. $id2=$this->questionList[$pos2];
  691. // exits foreach()
  692. break;
  693. }
  694. }
  695. */
  696. $question_list =array();
  697. foreach($this->questionList as $position=>$questionId)
  698. {
  699. $question_list[]= $questionId;
  700. }
  701. $len=count($question_list);
  702. $orderlist=array_keys($this->questionList);
  703. for($i=0;$i<$len;$i++)
  704. {
  705. $questionId = $question_list[$i];
  706. if($questionId == $id)
  707. {
  708. $pos1=$orderlist[$i+1];
  709. $pos2 =$orderlist[$i];
  710. if(!$pos2)
  711. {
  712. //echo 'cant move!';
  713. }
  714. break;
  715. }
  716. }
  717. // permutes questions in the array
  718. $temp=$this->questionList[$pos2];
  719. $this->questionList[$pos2]=$this->questionList[$pos1];
  720. $this->questionList[$pos1]=$temp;
  721. }
  722. /**
  723. * adds a question into the question list
  724. *
  725. * @author - Olivier Brouckaert
  726. * @param - integer $questionId - question ID
  727. * @return - boolean - true if the question has been added, otherwise false
  728. */
  729. function addToList($questionId)
  730. {
  731. // checks if the question ID is not in the list
  732. if(!$this->isInList($questionId))
  733. {
  734. // selects the max position
  735. if(!$this->selectNbrQuestions())
  736. {
  737. $pos=1;
  738. }
  739. else
  740. {
  741. if (is_array($this->questionList))
  742. $pos=max(array_keys($this->questionList))+1;
  743. }
  744. $this->questionList[$pos]=$questionId;
  745. return true;
  746. }
  747. return false;
  748. }
  749. /**
  750. * removes a question from the question list
  751. *
  752. * @author - Olivier Brouckaert
  753. * @param - integer $questionId - question ID
  754. * @return - boolean - true if the question has been removed, otherwise false
  755. */
  756. function removeFromList($questionId)
  757. {
  758. // searches the position of the question ID in the list
  759. $pos=array_search($questionId,$this->questionList);
  760. // question not found
  761. if($pos === false)
  762. {
  763. return false;
  764. }
  765. else
  766. {
  767. // deletes the position from the array containing the wanted question ID
  768. unset($this->questionList[$pos]);
  769. return true;
  770. }
  771. }
  772. /**
  773. * deletes the exercise from the database
  774. * Notice : leaves the question in the data base
  775. *
  776. * @author - Olivier Brouckaert
  777. */
  778. function delete(){
  779. global $_course,$_user;
  780. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  781. $sql="UPDATE $TBL_EXERCICES SET active='-1' WHERE id='".Database::escape_string($this->id)."'";
  782. Database::query($sql);
  783. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizDeleted',$_user['user_id']);
  784. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian') ) {
  785. $this -> search_engine_delete();
  786. }
  787. }
  788. /**
  789. * Creates the form to create / edit an exercise
  790. * @param FormValidator $form the formvalidator instance (by reference)
  791. */
  792. function createForm ($form, $type='full')
  793. {
  794. global $id;
  795. if(empty($type)){
  796. $type='full';
  797. }
  798. // form title
  799. if (!empty($_GET['exerciseId'])) {
  800. $form_title = get_lang('ModifyExercise');
  801. } else {
  802. $form_title = get_lang('NewEx');
  803. }
  804. $form->addElement('header', '', $form_title);
  805. // title
  806. $form -> addElement('text', 'exerciseTitle', get_lang('ExerciseName'),'class="input_titles" id="exercise_title"');
  807. //$form->applyFilter('exerciseTitle','html_filter');
  808. $form -> addElement('html','<div class="row">
  809. <div class="label"></div>
  810. <div class="formw" style="height:50px">
  811. <a href="javascript://" onclick=" return show_media()"> <span id="media_icon"> <img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('ExerciseDescription').'</span></a>
  812. </div>
  813. </div>');
  814. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  815. if(is_array($type)){
  816. $editor_config = array_merge($editor_config, $type);
  817. }
  818. $form -> addElement ('html','<div class="HideFCKEditor" id="HiddenFCKexerciseDescription" >');
  819. $form -> add_html_editor('exerciseDescription', get_lang('langExerciseDescription'), false, false, $editor_config);
  820. $form -> addElement ('html','</div>');
  821. $form -> addElement('html','<div class="row">
  822. <div class="label">&nbsp;</div>
  823. <div class="formw">
  824. <a href="javascript://" onclick=" return advanced_parameters()"><span id="img_plus_and_minus"><div style="vertical-align:top;" ><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'</div></span></a>
  825. </div>
  826. </div>');
  827. // Random questions
  828. $form -> addElement('html','<div id="options" style="display:none">');
  829. if($type=='full') {
  830. // feedback type
  831. $radios_feedback = array();
  832. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0');
  833. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2');
  834. $form -> addGroup($radios_feedback, null, get_lang('FeedbackType'));
  835. $feedback_option[0]=get_lang('ExerciseAtTheEndOfTheTest');
  836. $feedback_option[1]=get_lang('DirectFeedback');
  837. $feedback_option[2]=get_lang('NoFeedback');
  838. //Can't modify a DirectFeedback question
  839. if ($this->selectFeedbackType() != 1 ) {
  840. // $form -> addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  841. // test type
  842. $radios = array();
  843. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('QuestionsPerPageOne'),'2','onclick = "check_per_page_one() " ');
  844. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('QuestionsPerPageAll'),'1',array('onclick' => 'check_per_page_all()', 'id'=>'OptionPageAll'));
  845. $form -> addGroup($radios, null, get_lang('QuestionsPerPage'));
  846. } else {
  847. // if is Directfeedback but has not questions we can allow to modify the question type
  848. if ($this->selectNbrQuestions()== 0) {
  849. $form -> addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  850. // test type
  851. $radios = array();
  852. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SimpleExercise'),'1');
  853. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2');
  854. $form -> addGroup($radios, null, get_lang('ExerciseType'));
  855. } else {
  856. //we force the options to the DirectFeedback exercisetype
  857. $form -> addElement('hidden', 'exerciseFeedbackType','1');
  858. $form -> addElement('hidden', 'exerciseType','2');
  859. }
  860. }
  861. $radios_results_disabled = array();
  862. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('Yes'),'0');
  863. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('No'),'1');
  864. $form -> addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'));
  865. $random = array();
  866. $option=array();
  867. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10 ;
  868. $option = range(0,$max);
  869. $option[0]=get_lang('No');
  870. $random[] = FormValidator :: createElement ('select', 'randomQuestions',null,$option);
  871. $random[] = FormValidator :: createElement ('static', 'help','help','<span style="font-style: italic;">'.get_lang('RandomQuestionsHelp').'</span>');
  872. //$random[] = FormValidator :: createElement ('text', 'randomQuestions', null,null,'0');
  873. $form -> addGroup($random,null,get_lang('RandomQuestions'),'<br />');
  874. //random answers
  875. $radios_random_answers = array();
  876. $radios_random_answers[] = FormValidator :: createElement ('radio', 'randomAnswers', null, get_lang('Yes'),'1');
  877. $radios_random_answers[] = FormValidator :: createElement ('radio', 'randomAnswers', null, get_lang('No'),'0');
  878. $form -> addGroup($radios_random_answers, null, get_lang('RandomAnswers'));
  879. //Attempts
  880. $attempt_option=range(0,10);
  881. $attempt_option[0]=get_lang('Infinite');
  882. $form -> addElement('select', 'exerciseAttempts',get_lang('ExerciseAttempts'),$attempt_option);
  883. $form -> addElement('checkbox', 'enabletimelimit',get_lang('EnableTimeLimits'),null,'onclick = " return timelimit() "');
  884. $var= Exercise::selectTimeLimit();
  885. if(($this -> start_time!='0000-00-00 00:00:00')||($this -> end_time!='0000-00-00 00:00:00'))
  886. $form -> addElement('html','<div id="options2" style="display:block;">');
  887. else
  888. $form -> addElement('html','<div id="options2" style="display:none;">');
  889. //$form -> addElement('date', 'start_time', get_lang('ExeStartTime'), array('language'=>'es','format' => 'dMYHi'));
  890. //$form -> addElement('date', 'end_time', get_lang('ExeEndTime'), array('language'=>'es','format' => 'dMYHi'));
  891. $form->addElement('datepicker', 'start_time', get_lang('ExeStartTime'), array('form_name'=>'exercise_admin'), 5);
  892. $form->addElement('datepicker', 'end_time', get_lang('ExeEndTime'), array('form_name'=>'exercise_admin'), 5);
  893. //$form -> addElement('select', 'enabletimercontroltotalminutes',get_lang('ExerciseTimerControlMinutes'),$time_minutes_option);
  894. $form -> addElement('html','</div>');
  895. $check_option=$this -> selectType();
  896. // var_dump($check_option);
  897. if ($check_option==1 && isset($_GET['exerciseId'])) {
  898. $diplay = 'none';
  899. } else {
  900. $diplay = 'block';
  901. }
  902. $form -> addElement('html','<div id="divtimecontrol" style="display:'.$diplay.';">');
  903. //Timer control
  904. $time_hours_option = range(0,12);
  905. $time_minutes_option = range(0,59);
  906. $form -> addElement('checkbox', 'enabletimercontrol',get_lang('EnableTimerControl'),null,array('onclick' =>'option_time_expired()','id'=>'enabletimercontrol','onload'=>'check_load_time()'));
  907. $expired_date = (int)$this->selectExpiredTime();
  908. if(($expired_date!='0')) {
  909. $form -> addElement('html','<div id="timercontrol" style="display:block;">');
  910. } else {
  911. $form -> addElement('html','<div id="timercontrol" style="display:none;">');
  912. }
  913. $form -> addElement('text', 'enabletimercontroltotalminutes',get_lang('ExerciseTotalDurationInMinutes'),array('style' => 'width : 35px','id' => 'enabletimercontroltotalminutes'));
  914. $form -> addElement('html','</div>');
  915. //$form -> addElement('text', 'exerciseAttempts', get_lang('ExerciseAttempts').' : ',array('size'=>'2'));
  916. $form -> addElement('html','</div>'); //End advanced setting
  917. $form -> addElement('html','</div>');
  918. $defaults = array();
  919. if (api_get_setting('search_enabled') === 'true') {
  920. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  921. $form -> addElement ('checkbox', 'index_document','', get_lang('SearchFeatureDoIndexDocument'));
  922. $form -> addElement ('html','<br /><div class="row">');
  923. $form -> addElement ('html', '<div class="label">'. get_lang('SearchFeatureDocumentLanguage') .'</div>');
  924. $form -> addElement ('html', '<div class="formw">'. api_get_languages_combo() .'</div>');
  925. $form -> addElement ('html','</div><div class="sub-form">');
  926. $specific_fields = get_specific_field_list();
  927. foreach ($specific_fields as $specific_field) {
  928. $form -> addElement ('text', $specific_field['code'], $specific_field['name']);
  929. $filter = array('course_code'=> "'". api_get_course_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $this->id, 'tool_id' => '\''. TOOL_QUIZ .'\'');
  930. $values = get_specific_field_values_list($filter, array('value'));
  931. if ( !empty($values) ) {
  932. $arr_str_values = array();
  933. foreach ($values as $value) {
  934. $arr_str_values[] = $value['value'];
  935. }
  936. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  937. }
  938. }
  939. $form -> addElement ('html','</div>');
  940. }
  941. }
  942. // submit
  943. isset($_GET['exerciseId'])?$text=get_lang('ModifyExercise'):$text=get_lang('ProcedToQuestions');
  944. $form -> addElement('html', '<br /><br />');
  945. $form -> addElement('style_submit_button', 'submitExercise', $text, 'class="save"');
  946. $form -> addRule ('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  947. if($type=='full') {
  948. // rules
  949. $form -> addRule ('exerciseAttempts', get_lang('Numeric'), 'numeric');
  950. $form -> addRule ('start_time', get_lang('InvalidDate'), 'date');
  951. $form -> addRule ('end_time', get_lang('InvalidDate'), 'date');
  952. $form -> addRule(array ('start_time', 'end_time'), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
  953. }
  954. // defaults
  955. if($type=='full') {
  956. if($this -> id > 0) {
  957. if ($this -> random > $this->selectNbrQuestions()) {
  958. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  959. } else {
  960. $defaults['randomQuestions'] = $this -> random;
  961. }
  962. $defaults['randomAnswers'] = $this ->selectRandomAnswers();
  963. $defaults['exerciseType'] = $this -> selectType();
  964. $defaults['exerciseTitle'] = $this -> selectTitle();
  965. $defaults['exerciseDescription'] = $this -> selectDescription();
  966. $defaults['exerciseAttempts'] = $this->selectAttempts();
  967. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  968. $defaults['results_disabled'] = $this->selectResultsDisabled();
  969. if(($this -> start_time!='0000-00-00 00:00:00')||($this -> end_time!='0000-00-00 00:00:00'))
  970. $defaults['enabletimelimit'] = 1;
  971. $defaults['start_time'] = ($this->start_time!='0000-00-00 00:00:00')? $this -> start_time : date('Y-m-d 12:00:00');
  972. $defaults['end_time'] = ($this->end_time!='0000-00-00 00:00:00')?$this -> end_time : date('Y-m-d 12:00:00',time()+84600);
  973. //Get expired time
  974. if($this -> expired_time != '0') {
  975. $defaults['enabletimercontrol'] = 1;
  976. $defaults['enabletimercontroltotalminutes'] = $this -> expired_time;
  977. } else {
  978. $defaults['enabletimercontroltotalminutes'] = 0;
  979. }
  980. } else {
  981. $defaults['exerciseType'] = 2;
  982. $defaults['exerciseAttempts'] = 0;
  983. $defaults['randomQuestions'] = 0;
  984. $defaults['randomAnswers'] = 0;
  985. $defaults['exerciseDescription'] = '';
  986. $defaults['exerciseFeedbackType'] = 0;
  987. $defaults['results_disabled'] = 0;
  988. $defaults['start_time'] = date('Y-m-d 12:00:00');
  989. $defaults['end_time'] = date('Y-m-d 12:00:00',time()+84600);
  990. }
  991. } else {
  992. $defaults['exerciseTitle'] = $this -> selectTitle();
  993. $defaults['exerciseDescription'] = $this -> selectDescription();
  994. }
  995. if (api_get_setting('search_enabled') === 'true') {
  996. $defaults['index_document'] = 'checked="checked"';
  997. }
  998. $form -> setDefaults($defaults);
  999. }
  1000. /**
  1001. * function which process the creation of exercises
  1002. * @param FormValidator $form the formvalidator instance
  1003. */
  1004. function processCreation($form,$type='')
  1005. {
  1006. $this -> updateTitle($form -> getSubmitValue('exerciseTitle'));
  1007. $this -> updateDescription($form -> getSubmitValue('exerciseDescription'));
  1008. $this -> updateAttempts($form -> getSubmitValue('exerciseAttempts'));
  1009. $this -> updateFeedbackType($form -> getSubmitValue('exerciseFeedbackType'));
  1010. $this -> updateType($form -> getSubmitValue('exerciseType'));
  1011. $this -> setRandom($form -> getSubmitValue('randomQuestions'));
  1012. $this -> updateRandomAnswers($form -> getSubmitValue('randomAnswers'));
  1013. $this -> updateResultsDisabled($form -> getSubmitValue('results_disabled'));
  1014. $this -> updateExpiredTime($form -> getSubmitValue('enabletimercontroltotalminutes'));
  1015. if($form -> getSubmitValue('enabletimelimit')==1) {
  1016. $start_time = $form -> getSubmitValue('start_time');
  1017. $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
  1018. $end_time = $form -> getSubmitValue('end_time');
  1019. $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
  1020. } else {
  1021. $this->start_time = '0000-00-00 00:00:00';
  1022. $this->end_time = '0000-00-00 00:00:00';
  1023. }
  1024. if($form -> getSubmitValue('enabletimercontrol') == 1) {
  1025. $expired_total_time = $form -> getSubmitValue('enabletimercontroltotalminutes');
  1026. if ($this->expired_time == 0) {
  1027. $this->expired_time = $expired_total_time;
  1028. }
  1029. } else {
  1030. $this->expired_time = 0;
  1031. }
  1032. if($form -> getSubmitValue('randomAnswers') == 1) {
  1033. $this->random_answers=1;
  1034. } else {
  1035. $this->random_answers=0;
  1036. }
  1037. $this -> save($type);
  1038. }
  1039. function search_engine_save() {
  1040. if ($_POST['index_document'] != 1) {
  1041. return;
  1042. }
  1043. $course_id = api_get_course_id();
  1044. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  1045. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  1046. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  1047. $specific_fields = get_specific_field_list();
  1048. $ic_slide = new IndexableChunk();
  1049. $all_specific_terms = '';
  1050. foreach ($specific_fields as $specific_field) {
  1051. if (isset($_REQUEST[$specific_field['code']])) {
  1052. $sterms = trim($_REQUEST[$specific_field['code']]);
  1053. if (!empty($sterms)) {
  1054. $all_specific_terms .= ' '. $sterms;
  1055. $sterms = explode(',', $sterms);
  1056. foreach ($sterms as $sterm) {
  1057. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1058. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1059. }
  1060. }
  1061. }
  1062. }
  1063. // build the chunk to index
  1064. $ic_slide->addValue("title", $this->exercise);
  1065. $ic_slide->addCourseId($course_id);
  1066. $ic_slide->addToolId(TOOL_QUIZ);
  1067. $xapian_data = array(
  1068. SE_COURSE_ID => $course_id,
  1069. SE_TOOL_ID => TOOL_QUIZ,
  1070. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1071. SE_USER => (int)api_get_user_id(),
  1072. );
  1073. $ic_slide->xapian_data = serialize($xapian_data);
  1074. $exercise_description = $all_specific_terms .' '. $this->description;
  1075. $ic_slide->addValue("content", $exercise_description);
  1076. $di = new DokeosIndexer();
  1077. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  1078. $di->connectDb(NULL, NULL, $lang);
  1079. $di->addChunk($ic_slide);
  1080. //index and return search engine document id
  1081. $did = $di->index();
  1082. if ($did) {
  1083. // save it to db
  1084. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1085. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1086. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1087. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1088. Database::query($sql);
  1089. }
  1090. }
  1091. function search_engine_edit() {
  1092. // update search enchine and its values table if enabled
  1093. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  1094. $course_id = api_get_course_id();
  1095. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  1096. // get search_did
  1097. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1098. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  1099. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1100. $res = Database::query($sql);
  1101. if (Database::num_rows($res) > 0) {
  1102. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  1103. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  1104. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  1105. $se_ref = Database::fetch_array($res);
  1106. $specific_fields = get_specific_field_list();
  1107. $ic_slide = new IndexableChunk();
  1108. $all_specific_terms = '';
  1109. foreach ($specific_fields as $specific_field) {
  1110. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  1111. if (isset($_REQUEST[$specific_field['code']])) {
  1112. $sterms = trim($_REQUEST[$specific_field['code']]);
  1113. $all_specific_terms .= ' '. $sterms;
  1114. $sterms = explode(',', $sterms);
  1115. foreach ($sterms as $sterm) {
  1116. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1117. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1118. }
  1119. }
  1120. }
  1121. // build the chunk to index
  1122. $ic_slide->addValue("title", $this->exercise);
  1123. $ic_slide->addCourseId($course_id);
  1124. $ic_slide->addToolId(TOOL_QUIZ);
  1125. $xapian_data = array(
  1126. SE_COURSE_ID => $course_id,
  1127. SE_TOOL_ID => TOOL_QUIZ,
  1128. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1129. SE_USER => (int)api_get_user_id(),
  1130. );
  1131. $ic_slide->xapian_data = serialize($xapian_data);
  1132. $exercise_description = $all_specific_terms .' '. $this->description;
  1133. $ic_slide->addValue("content", $exercise_description);
  1134. $di = new DokeosIndexer();
  1135. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  1136. $di->connectDb(NULL, NULL, $lang);
  1137. $di->remove_document((int)$se_ref['search_did']);
  1138. $di->addChunk($ic_slide);
  1139. //index and return search engine document id
  1140. $did = $di->index();
  1141. if ($did) {
  1142. // save it to db
  1143. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  1144. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1145. Database::query($sql);
  1146. //var_dump($sql);
  1147. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1148. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1149. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1150. Database::query($sql);
  1151. }
  1152. }
  1153. }
  1154. }
  1155. function search_engine_delete() {
  1156. // remove from search engine if enabled
  1157. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian') ) {
  1158. $course_id = api_get_course_id();
  1159. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1160. $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';
  1161. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1162. $res = Database::query($sql);
  1163. if (Database::num_rows($res) > 0) {
  1164. $row = Database::fetch_array($res);
  1165. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  1166. $di = new DokeosIndexer();
  1167. $di->remove_document((int)$row['search_did']);
  1168. unset($di);
  1169. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1170. foreach ( $this->questionList as $question_i) {
  1171. $sql = 'SELECT type FROM %s WHERE id=%s';
  1172. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  1173. $qres = Database::query($sql);
  1174. if (Database::num_rows($qres) > 0) {
  1175. $qrow = Database::fetch_array($qres);
  1176. $objQuestion = Question::getInstance($qrow['type']);
  1177. $objQuestion = Question::read((int)$question_i);
  1178. $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
  1179. unset($objQuestion);
  1180. }
  1181. }
  1182. }
  1183. $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';
  1184. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1185. Database::query($sql);
  1186. // remove terms from db
  1187. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  1188. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  1189. }
  1190. }
  1191. function selectExpiredTime() {
  1192. return $this->expired_time;
  1193. }
  1194. /**
  1195. * Cleans the student's results only for the Exercise tool.
  1196. * The LP results are NOT deleted
  1197. * Works with exercises in sessions
  1198. * @return int quantity of user's exercises deleted
  1199. */
  1200. function clean_results() {
  1201. $table_track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1202. $table_track_e_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1203. $sql_select = "SELECT exe_id FROM $table_track_e_exercises
  1204. WHERE exe_cours_id = '".api_get_course_id()."' AND exe_exo_id = ".$this->id." AND orig_lp_id = 0 AND orig_lp_item_id = 0 AND session_id = ".api_get_session_id()."";
  1205. $result = Database::query($sql_select);
  1206. $exe_list = Database::store_result($result);
  1207. //deleting TRACK_E_ATTEMPT table
  1208. $i = 0;
  1209. if (is_array($exe_list) && count($exe_list) > 0) {
  1210. foreach($exe_list as $item) {
  1211. $sql = "DELETE FROM $table_track_e_attempt WHERE exe_id = '".$item['exe_id']."'";
  1212. Database::query($sql);
  1213. $i++;
  1214. }
  1215. }
  1216. //delete TRACK_E_EXERCICES table
  1217. $sql = "DELETE FROM $table_track_e_exercises
  1218. WHERE exe_cours_id = '".api_get_course_id()."' AND exe_exo_id = ".$this->id." AND orig_lp_id = 0 AND orig_lp_item_id = 0 AND session_id = ".api_get_session_id()."";
  1219. Database::query($sql);
  1220. return $i;
  1221. }
  1222. /**
  1223. * Copies an exercise (duplicate all questions and answers)
  1224. */
  1225. public function copy_exercise() {
  1226. $exercise_obj= new Exercise();
  1227. $exercise_obj = $this;
  1228. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1229. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1230. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1231. // force the creation of a new exercise
  1232. $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
  1233. //Hides the new exercise
  1234. $exercise_obj->updateStatus(false);
  1235. $exercise_obj->updateId(0);
  1236. $exercise_obj->save();
  1237. $new_exercise_id = $exercise_obj->selectId();
  1238. $question_list = $exercise_obj->selectQuestionList();
  1239. //Question creation
  1240. foreach ($question_list as $old_question_id) {
  1241. $old_question_obj = Question::read($old_question_id);
  1242. $new_id = $old_question_obj->duplicate();
  1243. $new_question_obj = Question::read($new_id);
  1244. $new_question_obj->addToList($new_exercise_id);
  1245. // This should be moved to the duplicate function
  1246. $new_answer_obj = new Answer($old_question_id);
  1247. $new_answer_obj->read();
  1248. $new_answer_obj->duplicate($new_id);
  1249. }
  1250. }
  1251. /**
  1252. * Changes the exercise id
  1253. *
  1254. * @param - in $id - exercise id
  1255. */
  1256. private function updateId($id) {
  1257. $this->id = $id;
  1258. }
  1259. /**
  1260. * Changes the exercise status
  1261. *
  1262. * @param - string $status - exercise status
  1263. */
  1264. function updateStatus($status)
  1265. {
  1266. $this->active = $status;
  1267. }
  1268. }
  1269. endif;
  1270. ?>