exercise.class.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  1. <?php
  2. /* For licensing terms, see /dokeos_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']==true && $_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. /*
  511. title='".Database::escape_string(Security::remove_XSS($exercise))."',
  512. description='".Database::escape_string(Security::remove_XSS(api_html_entity_decode($description),COURSEMANAGERLOWSECURITY))."'";
  513. */
  514. $sql="UPDATE $TBL_EXERCICES SET
  515. title='".Database::escape_string($exercise)."',
  516. description='".Database::escape_string($description)."'";
  517. if ($type_e != 'simple') {
  518. $sql .= ", sound='".Database::escape_string($sound)."',
  519. type='".Database::escape_string($type)."',
  520. random='".Database::escape_string($random)."',
  521. random_answers='".Database::escape_string($random_answers)."',
  522. active='".Database::escape_string($active)."',
  523. feedback_type='".Database::escape_string($feedbacktype)."',
  524. start_time='$start_time',end_time='$end_time',
  525. max_attempt='".Database::escape_string($attempts)."',
  526. expired_time='".Database::escape_string($expired_time)."',
  527. results_disabled='".Database::escape_string($results_disabled)."'";
  528. }
  529. $sql .= " WHERE id='".Database::escape_string($id)."'";
  530. // echo $sql;
  531. Database::query($sql);
  532. // update into the item_property table
  533. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizUpdated',$_user['user_id']);
  534. if (api_get_setting('search_enabled')=='true') {
  535. $this -> search_engine_edit();
  536. }
  537. } else {// creates a new exercise
  538. //add condition by anonymous user
  539. /*if (!api_is_anonymous()) {
  540. //is course manager
  541. $cond1=Database::escape_string($exercise);
  542. $cond2=Database::escape_string($description);
  543. } else {
  544. //is anonymous user
  545. $cond1=Database::escape_string(Security::remove_XSS($exercise));
  546. $cond2=Database::escape_string(Security::remove_XSS(api_html_entity_decode($description),COURSEMANAGERLOWSECURITY));
  547. }*/
  548. $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)
  549. VALUES(
  550. '$start_time','$end_time',
  551. '".Database::escape_string($exercise)."',
  552. '".Database::escape_string($description)."',
  553. '".Database::escape_string($sound)."',
  554. '".Database::escape_string($type)."',
  555. '".Database::escape_string($random)."',
  556. '".Database::escape_string($random_answers)."',
  557. '".Database::escape_string($active)."',
  558. '".Database::escape_string($results_disabled)."',
  559. '".Database::escape_string($attempts)."',
  560. '".Database::escape_string($feedbacktype)."',
  561. '".Database::escape_string($expired_time)."',
  562. '".Database::escape_string($session_id)."'
  563. )";
  564. Database::query($sql);
  565. $this->id=Database::insert_id();
  566. // insert into the item_property table
  567. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizAdded',$_user['user_id']);
  568. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  569. $this -> search_engine_save();
  570. }
  571. }
  572. // updates the question position
  573. $this->update_question_positions();
  574. }
  575. function update_question_positions() {
  576. // updates the question position
  577. $TBL_QUIZ_QUESTION= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  578. foreach($this->questionList as $position=>$questionId)
  579. {
  580. //$sql="UPDATE $TBL_QUESTIONS SET position='".Database::escape_string($position)."' WHERE id='".Database::escape_string($questionId)."'";
  581. $sql="UPDATE $TBL_QUIZ_QUESTION SET question_order='".Database::escape_string($position)."' " .
  582. "WHERE question_id='".Database::escape_string($questionId)."' and exercice_id=".Database::escape_string($this->id)."";
  583. Database::query($sql);
  584. }
  585. }
  586. /**
  587. * moves a question up in the list
  588. *
  589. * @author - Olivier Brouckaert
  590. * @author - Julio Montoya (rewrote the code)
  591. * @param - integer $id - question ID to move up
  592. */
  593. function moveUp($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. echo $pos1=$position; //1
  606. echo "<br>";
  607. prev($this->questionList);
  608. prev($this->questionList);
  609. // position of previous question in the array
  610. $pos2=key($this->questionList);
  611. //if the cursor of the array hit the end
  612. // then we must reset the array to get the previous key
  613. if($pos2===null)
  614. {
  615. end($this->questionList);
  616. prev($this->questionList);
  617. $pos2=key($this->questionList);
  618. }
  619. // error, can't move question
  620. if(!$pos2)
  621. {
  622. //echo 'cant move!';
  623. $pos2=key($this->questionList);
  624. reset($this->questionList);
  625. }
  626. $id2=$this->questionList[$pos2];
  627. // exits foreach()
  628. break;
  629. }
  630. $i++;
  631. }
  632. */
  633. $question_list =array();
  634. foreach($this->questionList as $position=>$questionId)
  635. {
  636. $question_list[]= $questionId;
  637. }
  638. $len=count($question_list);
  639. $orderlist=array_keys($this->questionList);
  640. for($i=0;$i<$len;$i++)
  641. {
  642. $questionId = $question_list[$i];
  643. if($questionId == $id)
  644. {
  645. // position of question in the array
  646. $pos1=$orderlist[$i];
  647. $pos2=$orderlist[$i-1];
  648. if($pos2===null)
  649. {
  650. $pos2 = $orderlist[$len-1];
  651. }
  652. // error, can't move question
  653. if(!$pos2)
  654. {
  655. $pos2=$orderlist[0];
  656. $i=0;
  657. }
  658. break;
  659. }
  660. }
  661. // permutes questions in the array
  662. $temp=$this->questionList[$pos2];
  663. $this->questionList[$pos2]=$this->questionList[$pos1];
  664. $this->questionList[$pos1]=$temp;
  665. }
  666. /**
  667. * moves a question down in the list
  668. *
  669. * @author - Olivier Brouckaert
  670. * @param - integer $id - question ID to move down
  671. */
  672. function moveDown($id)
  673. {
  674. // there is a bug with some version of PHP with the key and prev functions
  675. // the script commented was tested in dev.dokeos.com with no success
  676. // Instead of using prev and next this was change with arrays.
  677. /*
  678. foreach($this->questionList as $position=>$questionId)
  679. {
  680. // if question ID found
  681. if($questionId == $id)
  682. {
  683. // position of question in the array
  684. $pos1=$position;
  685. //next($this->questionList);
  686. // position of next question in the array
  687. $pos2=key($this->questionList);
  688. // error, can't move question
  689. if(!$pos2)
  690. {
  691. //echo 'cant move!';
  692. return;
  693. }
  694. $id2=$this->questionList[$pos2];
  695. // exits foreach()
  696. break;
  697. }
  698. }
  699. */
  700. $question_list =array();
  701. foreach($this->questionList as $position=>$questionId)
  702. {
  703. $question_list[]= $questionId;
  704. }
  705. $len=count($question_list);
  706. $orderlist=array_keys($this->questionList);
  707. for($i=0;$i<$len;$i++)
  708. {
  709. $questionId = $question_list[$i];
  710. if($questionId == $id)
  711. {
  712. $pos1=$orderlist[$i+1];
  713. $pos2 =$orderlist[$i];
  714. if(!$pos2)
  715. {
  716. //echo 'cant move!';
  717. }
  718. break;
  719. }
  720. }
  721. // permutes questions in the array
  722. $temp=$this->questionList[$pos2];
  723. $this->questionList[$pos2]=$this->questionList[$pos1];
  724. $this->questionList[$pos1]=$temp;
  725. }
  726. /**
  727. * adds a question into the question list
  728. *
  729. * @author - Olivier Brouckaert
  730. * @param - integer $questionId - question ID
  731. * @return - boolean - true if the question has been added, otherwise false
  732. */
  733. function addToList($questionId)
  734. {
  735. // checks if the question ID is not in the list
  736. if(!$this->isInList($questionId))
  737. {
  738. // selects the max position
  739. if(!$this->selectNbrQuestions())
  740. {
  741. $pos=1;
  742. }
  743. else
  744. {
  745. if (is_array($this->questionList))
  746. $pos=max(array_keys($this->questionList))+1;
  747. }
  748. $this->questionList[$pos]=$questionId;
  749. return true;
  750. }
  751. return false;
  752. }
  753. /**
  754. * removes a question from the question list
  755. *
  756. * @author - Olivier Brouckaert
  757. * @param - integer $questionId - question ID
  758. * @return - boolean - true if the question has been removed, otherwise false
  759. */
  760. function removeFromList($questionId)
  761. {
  762. // searches the position of the question ID in the list
  763. $pos=array_search($questionId,$this->questionList);
  764. // question not found
  765. if($pos === false)
  766. {
  767. return false;
  768. }
  769. else
  770. {
  771. // deletes the position from the array containing the wanted question ID
  772. unset($this->questionList[$pos]);
  773. return true;
  774. }
  775. }
  776. /**
  777. * deletes the exercise from the database
  778. * Notice : leaves the question in the data base
  779. *
  780. * @author - Olivier Brouckaert
  781. */
  782. function delete(){
  783. global $_course,$_user;
  784. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  785. $sql="UPDATE $TBL_EXERCICES SET active='-1' WHERE id='".Database::escape_string($this->id)."'";
  786. Database::query($sql);
  787. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizDeleted',$_user['user_id']);
  788. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian') ) {
  789. $this -> search_engine_delete();
  790. }
  791. }
  792. /**
  793. * Creates the form to create / edit an exercise
  794. * @param FormValidator $form the formvalidator instance (by reference)
  795. */
  796. function createForm ($form, $type='full')
  797. {
  798. global $id;
  799. if(empty($type)){
  800. $type='full';
  801. }
  802. // form title
  803. if (!empty($_GET['exerciseId'])) {
  804. $form_title = get_lang('ModifyExercise');
  805. } else {
  806. $form_title = get_lang('NewEx');
  807. }
  808. $form->addElement('header', '', $form_title);
  809. // title
  810. $form -> addElement('text', 'exerciseTitle', get_lang('ExerciseName'),'class="input_titles" id="exercise_title"');
  811. //$form->applyFilter('exerciseTitle','html_filter');
  812. $form -> addElement('html','<div class="row">
  813. <div class="label"></div>
  814. <div class="formw" style="height:50px">
  815. <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>
  816. </div>
  817. </div>');
  818. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  819. if(is_array($type)){
  820. $editor_config = array_merge($editor_config, $type);
  821. }
  822. $form -> addElement ('html','<div class="HideFCKEditor" id="HiddenFCKexerciseDescription" >');
  823. $form -> add_html_editor('exerciseDescription', get_lang('langExerciseDescription'), false, false, $editor_config);
  824. $form -> addElement ('html','</div>');
  825. $form -> addElement('html','<div class="row">
  826. <div class="label">&nbsp;</div>
  827. <div class="formw">
  828. <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>
  829. </div>
  830. </div>');
  831. // Random questions
  832. $form -> addElement('html','<div id="options" style="display:none">');
  833. if($type=='full') {
  834. // feedback type
  835. $radios_feedback = array();
  836. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0');
  837. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2');
  838. $form -> addGroup($radios_feedback, null, get_lang('FeedbackType'));
  839. $feedback_option[0]=get_lang('ExerciseAtTheEndOfTheTest');
  840. $feedback_option[1]=get_lang('DirectFeedback');
  841. $feedback_option[2]=get_lang('NoFeedback');
  842. //Can't modify a DirectFeedback question
  843. if ($this->selectFeedbackType() != 1 ) {
  844. // $form -> addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  845. // test type
  846. $radios = array();
  847. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('QuestionsPerPageOne'),'2','onclick = "check_per_page_one() " ');
  848. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('QuestionsPerPageAll'),'1',array('onclick' => 'check_per_page_all()', 'id'=>'OptionPageAll'));
  849. $form -> addGroup($radios, null, get_lang('QuestionsPerPage'));
  850. } else {
  851. // if is Directfeedback but has not questions we can allow to modify the question type
  852. if ($this->selectNbrQuestions()== 0) {
  853. $form -> addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  854. // test type
  855. $radios = array();
  856. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SimpleExercise'),'1');
  857. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2');
  858. $form -> addGroup($radios, null, get_lang('ExerciseType'));
  859. } else {
  860. //we force the options to the DirectFeedback exercisetype
  861. $form -> addElement('hidden', 'exerciseFeedbackType','1');
  862. $form -> addElement('hidden', 'exerciseType','2');
  863. }
  864. }
  865. $radios_results_disabled = array();
  866. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('Yes'),'0');
  867. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('No'),'1');
  868. $form -> addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'));
  869. $random = array();
  870. $option=array();
  871. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10 ;
  872. $option = range(0,$max);
  873. $option[0]=get_lang('No');
  874. $random[] = FormValidator :: createElement ('select', 'randomQuestions',null,$option);
  875. $random[] = FormValidator :: createElement ('static', 'help','help','<span style="font-style: italic;">'.get_lang('RandomQuestionsHelp').'</span>');
  876. //$random[] = FormValidator :: createElement ('text', 'randomQuestions', null,null,'0');
  877. $form -> addGroup($random,null,get_lang('RandomQuestions'),'<br />');
  878. //random answers
  879. $radios_random_answers = array();
  880. $radios_random_answers[] = FormValidator :: createElement ('radio', 'randomAnswers', null, get_lang('Yes'),'1');
  881. $radios_random_answers[] = FormValidator :: createElement ('radio', 'randomAnswers', null, get_lang('No'),'0');
  882. $form -> addGroup($radios_random_answers, null, get_lang('RandomAnswers'));
  883. //Attempts
  884. $attempt_option=range(0,10);
  885. $attempt_option[0]=get_lang('Infinite');
  886. $form -> addElement('select', 'exerciseAttempts',get_lang('ExerciseAttempts'),$attempt_option);
  887. $form -> addElement('checkbox', 'enabletimelimit',get_lang('EnableTimeLimits'),null,'onclick = " return timelimit() "');
  888. $var= Exercise::selectTimeLimit();
  889. if(($this -> start_time!='0000-00-00 00:00:00')||($this -> end_time!='0000-00-00 00:00:00'))
  890. $form -> addElement('html','<div id="options2" style="display:block;">');
  891. else
  892. $form -> addElement('html','<div id="options2" style="display:none;">');
  893. //$form -> addElement('date', 'start_time', get_lang('ExeStartTime'), array('language'=>'es','format' => 'dMYHi'));
  894. //$form -> addElement('date', 'end_time', get_lang('ExeEndTime'), array('language'=>'es','format' => 'dMYHi'));
  895. $form->addElement('datepicker', 'start_time', get_lang('ExeStartTime'), array('form_name'=>'exercise_admin'));
  896. $form->addElement('datepicker', 'end_time', get_lang('ExeEndTime'), array('form_name'=>'exercise_admin'));
  897. //$form -> addElement('select', 'enabletimercontroltotalminutes',get_lang('ExerciseTimerControlMinutes'),$time_minutes_option);
  898. $form -> addElement('html','</div>');
  899. $check_option=$this -> selectType();
  900. // var_dump($check_option);
  901. if ($check_option==1 && isset($_GET['exerciseId'])) {
  902. $diplay = 'none';
  903. } else {
  904. $diplay = 'block';
  905. }
  906. $form -> addElement('html','<div id="divtimecontrol" style="display:'.$diplay.';">');
  907. //Timer control
  908. $time_hours_option = range(0,12);
  909. $time_minutes_option = range(0,59);
  910. $form -> addElement('checkbox', 'enabletimercontrol',get_lang('EnableTimerControl'),null,array('onclick' =>'option_time_expired()','id'=>'enabletimercontrol','onload'=>'check_load_time()'));
  911. $expired_date = (int)$this->selectExpiredTime();
  912. if(($expired_date!='0')) {
  913. $form -> addElement('html','<div id="timercontrol" style="display:block;">');
  914. } else {
  915. $form -> addElement('html','<div id="timercontrol" style="display:none;">');
  916. }
  917. $form -> addElement('text', 'enabletimercontroltotalminutes',get_lang('ExerciseTotalDurationInMinutes'),array('style' => 'width : 35px','id' => 'enabletimercontroltotalminutes'));
  918. $form -> addElement('html','</div>');
  919. //$form -> addElement('text', 'exerciseAttempts', get_lang('ExerciseAttempts').' : ',array('size'=>'2'));
  920. $form -> addElement('html','</div>'); //End advanced setting
  921. $form -> addElement('html','</div>');
  922. $defaults = array();
  923. if (api_get_setting('search_enabled') === 'true') {
  924. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  925. $form -> addElement ('checkbox', 'index_document','', get_lang('SearchFeatureDoIndexDocument'));
  926. $form -> addElement ('html','<br /><div class="row">');
  927. $form -> addElement ('html', '<div class="label">'. get_lang('SearchFeatureDocumentLanguage') .'</div>');
  928. $form -> addElement ('html', '<div class="formw">'. api_get_languages_combo() .'</div>');
  929. $form -> addElement ('html','</div><div class="sub-form">');
  930. $specific_fields = get_specific_field_list();
  931. foreach ($specific_fields as $specific_field) {
  932. $form -> addElement ('text', $specific_field['code'], $specific_field['name']);
  933. $filter = array('course_code'=> "'". api_get_course_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $this->id, 'tool_id' => '\''. TOOL_QUIZ .'\'');
  934. $values = get_specific_field_values_list($filter, array('value'));
  935. if ( !empty($values) ) {
  936. $arr_str_values = array();
  937. foreach ($values as $value) {
  938. $arr_str_values[] = $value['value'];
  939. }
  940. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  941. }
  942. }
  943. $form -> addElement ('html','</div>');
  944. }
  945. }
  946. // submit
  947. isset($_GET['exerciseId'])?$text=get_lang('ModifyExercise'):$text=get_lang('ProcedToQuestions');
  948. $form -> addElement('html', '<br /><br />');
  949. $form -> addElement('style_submit_button', 'submitExercise', $text, 'class="save"');
  950. $form -> addRule ('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  951. if($type=='full') {
  952. // rules
  953. $form -> addRule ('exerciseAttempts', get_lang('Numeric'), 'numeric');
  954. $form -> addRule ('start_time', get_lang('InvalidDate'), 'date');
  955. $form -> addRule ('end_time', get_lang('InvalidDate'), 'date');
  956. $form -> addRule(array ('start_time', 'end_time'), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
  957. }
  958. // defaults
  959. if($type=='full') {
  960. if($this -> id > 0) {
  961. if ($this -> random > $this->selectNbrQuestions()) {
  962. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  963. } else {
  964. $defaults['randomQuestions'] = $this -> random;
  965. }
  966. $defaults['randomAnswers'] = $this ->selectRandomAnswers();
  967. $defaults['exerciseType'] = $this -> selectType();
  968. $defaults['exerciseTitle'] = $this -> selectTitle();
  969. $defaults['exerciseDescription'] = $this -> selectDescription();
  970. $defaults['exerciseAttempts'] = $this->selectAttempts();
  971. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  972. $defaults['results_disabled'] = $this->selectResultsDisabled();
  973. if(($this -> start_time!='0000-00-00 00:00:00')||($this -> end_time!='0000-00-00 00:00:00'))
  974. $defaults['enabletimelimit'] = 1;
  975. $defaults['start_time'] = ($this->start_time!='0000-00-00 00:00:00')? $this -> start_time : date('Y-m-d 12:00:00');
  976. $defaults['end_time'] = ($this->end_time!='0000-00-00 00:00:00')?$this -> end_time : date('Y-m-d 12:00:00',time()+84600);
  977. //Get expired time
  978. if($this -> expired_time != '0') {
  979. $defaults['enabletimercontrol'] = 1;
  980. $defaults['enabletimercontroltotalminutes'] = $this -> expired_time;
  981. } else {
  982. $defaults['enabletimercontroltotalminutes'] = 0;
  983. }
  984. } else {
  985. $defaults['exerciseType'] = 2;
  986. $defaults['exerciseAttempts'] = 0;
  987. $defaults['randomQuestions'] = 0;
  988. $defaults['randomAnswers'] = 0;
  989. $defaults['exerciseDescription'] = '';
  990. $defaults['exerciseFeedbackType'] = 0;
  991. $defaults['results_disabled'] = 0;
  992. $defaults['start_time'] = date('Y-m-d 12:00:00');
  993. $defaults['end_time'] = date('Y-m-d 12:00:00',time()+84600);
  994. }
  995. } else {
  996. $defaults['exerciseTitle'] = $this -> selectTitle();
  997. $defaults['exerciseDescription'] = $this -> selectDescription();
  998. }
  999. if (api_get_setting('search_enabled') === 'true') {
  1000. $defaults['index_document'] = 'checked="checked"';
  1001. }
  1002. $form -> setDefaults($defaults);
  1003. }
  1004. /**
  1005. * function which process the creation of exercises
  1006. * @param FormValidator $form the formvalidator instance
  1007. */
  1008. function processCreation($form,$type='')
  1009. {
  1010. $this -> updateTitle($form -> getSubmitValue('exerciseTitle'));
  1011. $this -> updateDescription($form -> getSubmitValue('exerciseDescription'));
  1012. $this -> updateAttempts($form -> getSubmitValue('exerciseAttempts'));
  1013. $this -> updateFeedbackType($form -> getSubmitValue('exerciseFeedbackType'));
  1014. $this -> updateType($form -> getSubmitValue('exerciseType'));
  1015. $this -> setRandom($form -> getSubmitValue('randomQuestions'));
  1016. $this -> updateRandomAnswers($form -> getSubmitValue('randomAnswers'));
  1017. $this -> updateResultsDisabled($form -> getSubmitValue('results_disabled'));
  1018. $this -> updateExpiredTime($form -> getSubmitValue('enabletimercontroltotalminutes'));
  1019. if($form -> getSubmitValue('enabletimelimit')==1) {
  1020. $start_time = $form -> getSubmitValue('start_time');
  1021. $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
  1022. $end_time = $form -> getSubmitValue('end_time');
  1023. $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
  1024. } else {
  1025. $this->start_time = '0000-00-00 00:00:00';
  1026. $this->end_time = '0000-00-00 00:00:00';
  1027. }
  1028. if($form -> getSubmitValue('enabletimercontrol') == 1) {
  1029. $expired_total_time = $form -> getSubmitValue('enabletimercontroltotalminutes');
  1030. if ($this->expired_time == 0) {
  1031. $this->expired_time = $expired_total_time;
  1032. }
  1033. } else {
  1034. $this->expired_time = 0;
  1035. }
  1036. if($form -> getSubmitValue('randomAnswers') == 1) {
  1037. $this->random_answers=1;
  1038. } else {
  1039. $this->random_answers=0;
  1040. }
  1041. $this -> save($type);
  1042. }
  1043. function search_engine_save() {
  1044. if ($_POST['index_document'] != 1) {
  1045. return;
  1046. }
  1047. $course_id = api_get_course_id();
  1048. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  1049. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  1050. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  1051. $specific_fields = get_specific_field_list();
  1052. $ic_slide = new IndexableChunk();
  1053. $all_specific_terms = '';
  1054. foreach ($specific_fields as $specific_field) {
  1055. if (isset($_REQUEST[$specific_field['code']])) {
  1056. $sterms = trim($_REQUEST[$specific_field['code']]);
  1057. if (!empty($sterms)) {
  1058. $all_specific_terms .= ' '. $sterms;
  1059. $sterms = explode(',', $sterms);
  1060. foreach ($sterms as $sterm) {
  1061. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1062. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1063. }
  1064. }
  1065. }
  1066. }
  1067. // build the chunk to index
  1068. $ic_slide->addValue("title", $this->exercise);
  1069. $ic_slide->addCourseId($course_id);
  1070. $ic_slide->addToolId(TOOL_QUIZ);
  1071. $xapian_data = array(
  1072. SE_COURSE_ID => $course_id,
  1073. SE_TOOL_ID => TOOL_QUIZ,
  1074. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1075. SE_USER => (int)api_get_user_id(),
  1076. );
  1077. $ic_slide->xapian_data = serialize($xapian_data);
  1078. $exercise_description = $all_specific_terms .' '. $this->description;
  1079. $ic_slide->addValue("content", $exercise_description);
  1080. $di = new DokeosIndexer();
  1081. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  1082. $di->connectDb(NULL, NULL, $lang);
  1083. $di->addChunk($ic_slide);
  1084. //index and return search engine document id
  1085. $did = $di->index();
  1086. if ($did) {
  1087. // save it to db
  1088. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1089. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1090. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1091. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1092. Database::query($sql);
  1093. }
  1094. }
  1095. function search_engine_edit() {
  1096. // update search enchine and its values table if enabled
  1097. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  1098. $course_id = api_get_course_id();
  1099. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  1100. // get search_did
  1101. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1102. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  1103. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1104. $res = Database::query($sql);
  1105. if (Database::num_rows($res) > 0) {
  1106. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  1107. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  1108. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  1109. $se_ref = Database::fetch_array($res);
  1110. $specific_fields = get_specific_field_list();
  1111. $ic_slide = new IndexableChunk();
  1112. $all_specific_terms = '';
  1113. foreach ($specific_fields as $specific_field) {
  1114. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  1115. if (isset($_REQUEST[$specific_field['code']])) {
  1116. $sterms = trim($_REQUEST[$specific_field['code']]);
  1117. $all_specific_terms .= ' '. $sterms;
  1118. $sterms = explode(',', $sterms);
  1119. foreach ($sterms as $sterm) {
  1120. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1121. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1122. }
  1123. }
  1124. }
  1125. // build the chunk to index
  1126. $ic_slide->addValue("title", $this->exercise);
  1127. $ic_slide->addCourseId($course_id);
  1128. $ic_slide->addToolId(TOOL_QUIZ);
  1129. $xapian_data = array(
  1130. SE_COURSE_ID => $course_id,
  1131. SE_TOOL_ID => TOOL_QUIZ,
  1132. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1133. SE_USER => (int)api_get_user_id(),
  1134. );
  1135. $ic_slide->xapian_data = serialize($xapian_data);
  1136. $exercise_description = $all_specific_terms .' '. $this->description;
  1137. $ic_slide->addValue("content", $exercise_description);
  1138. $di = new DokeosIndexer();
  1139. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  1140. $di->connectDb(NULL, NULL, $lang);
  1141. $di->remove_document((int)$se_ref['search_did']);
  1142. $di->addChunk($ic_slide);
  1143. //index and return search engine document id
  1144. $did = $di->index();
  1145. if ($did) {
  1146. // save it to db
  1147. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  1148. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1149. Database::query($sql);
  1150. //var_dump($sql);
  1151. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1152. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1153. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1154. Database::query($sql);
  1155. }
  1156. }
  1157. }
  1158. }
  1159. function search_engine_delete() {
  1160. // remove from search engine if enabled
  1161. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian') ) {
  1162. $course_id = api_get_course_id();
  1163. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1164. $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';
  1165. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1166. $res = Database::query($sql);
  1167. if (Database::num_rows($res) > 0) {
  1168. $row = Database::fetch_array($res);
  1169. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  1170. $di = new DokeosIndexer();
  1171. $di->remove_document((int)$row['search_did']);
  1172. unset($di);
  1173. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1174. foreach ( $this->questionList as $question_i) {
  1175. $sql = 'SELECT type FROM %s WHERE id=%s';
  1176. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  1177. $qres = Database::query($sql);
  1178. if (Database::num_rows($qres) > 0) {
  1179. $qrow = Database::fetch_array($qres);
  1180. $objQuestion = Question::getInstance($qrow['type']);
  1181. $objQuestion = Question::read((int)$question_i);
  1182. $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
  1183. unset($objQuestion);
  1184. }
  1185. }
  1186. }
  1187. $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';
  1188. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1189. Database::query($sql);
  1190. // remove terms from db
  1191. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  1192. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  1193. }
  1194. }
  1195. function selectExpiredTime() {
  1196. return $this->expired_time;
  1197. }
  1198. /**
  1199. * Cleans the student's results only for the Exercise tool.
  1200. * The LP results are NOT deleted
  1201. * Works with exercises in sessions
  1202. * @return int quantity of user's exercises deleted
  1203. */
  1204. function clean_results() {
  1205. $table_track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1206. $table_track_e_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1207. $sql_select = "SELECT exe_id FROM $table_track_e_exercises
  1208. 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()."";
  1209. $result = Database::query($sql_select);
  1210. $exe_list = Database::store_result($result);
  1211. //deleting TRACK_E_ATTEMPT table
  1212. $i = 0;
  1213. if (is_array($exe_list) && count($exe_list) > 0) {
  1214. foreach($exe_list as $item) {
  1215. $sql = "DELETE FROM $table_track_e_attempt WHERE exe_id = '".$item['exe_id']."'";
  1216. Database::query($sql);
  1217. $i++;
  1218. }
  1219. }
  1220. //delete TRACK_E_EXERCICES table
  1221. $sql = "DELETE FROM $table_track_e_exercises
  1222. 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()."";
  1223. Database::query($sql);
  1224. return $i;
  1225. }
  1226. /**
  1227. * Copies an exercise (duplicate all questions and answers)
  1228. */
  1229. public function copy_exercise() {
  1230. $exercise_obj= new Exercise();
  1231. $exercise_obj = $this;
  1232. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1233. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1234. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1235. // force the creation of a new exercise
  1236. $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
  1237. //Hides the new exercise
  1238. $exercise_obj->updateStatus(false);
  1239. $exercise_obj->updateId(0);
  1240. $exercise_obj->save();
  1241. $new_exercise_id = $exercise_obj->selectId();
  1242. $question_list = $exercise_obj->selectQuestionList();
  1243. //Question creation
  1244. foreach ($question_list as $old_question_id) {
  1245. $old_question_obj = Question::read($old_question_id);
  1246. $new_id = $old_question_obj->duplicate();
  1247. $new_question_obj = Question::read($new_id);
  1248. $new_question_obj->addToList($new_exercise_id);
  1249. // This should be moved to the duplicate function
  1250. $new_answer_obj = new Answer($old_question_id);
  1251. $new_answer_obj->read();
  1252. $new_answer_obj->duplicate($new_id);
  1253. }
  1254. }
  1255. /**
  1256. * Changes the exercise id
  1257. *
  1258. * @param - in $id - exercise id
  1259. */
  1260. private function updateId($id) {
  1261. $this->id = $id;
  1262. }
  1263. /**
  1264. * Changes the exercise status
  1265. *
  1266. * @param - string $status - exercise status
  1267. */
  1268. function updateStatus($status)
  1269. {
  1270. $this->active = $status;
  1271. }
  1272. }
  1273. endif;
  1274. ?>