question.class.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. <?php // $Id: question.class.php 22257 2009-07-20 17:50:09Z juliomontoya $
  2. /* For licensing terms, see /dokeos_license.txt */
  3. /**
  4. * File containing the Question class.
  5. * @package dokeos.exercise
  6. * @author Olivier Brouckaert
  7. * @version $Id: question.class.php 22257 2009-07-20 17:50:09Z juliomontoya $
  8. */
  9. if(!class_exists('Question')):
  10. // answer types
  11. define('UNIQUE_ANSWER', 1);
  12. define('MULTIPLE_ANSWER', 2);
  13. define('FILL_IN_BLANKS', 3);
  14. define('MATCHING', 4);
  15. define('FREE_ANSWER', 5);
  16. define('HOT_SPOT', 6);
  17. define('HOT_SPOT_ORDER', 7);
  18. /**
  19. CLASS QUESTION
  20. *
  21. * This class allows to instantiate an object of type Question
  22. *
  23. * @author Olivier Brouckaert, original author
  24. * @author Patrick Cool, LaTeX support
  25. * @package dokeos.exercise
  26. */
  27. abstract class Question
  28. {
  29. var $id;
  30. var $question;
  31. var $description;
  32. var $weighting;
  33. var $position;
  34. var $type;
  35. var $level;
  36. var $picture;
  37. var $exerciseList; // array with the list of exercises which this question is in
  38. static $typePicture = 'new_question.png';
  39. static $explanationLangVar = '';
  40. static $questionTypes = array(
  41. UNIQUE_ANSWER => array('unique_answer.class.php' , 'UniqueAnswer'),
  42. MULTIPLE_ANSWER => array('multiple_answer.class.php' , 'MultipleAnswer'),
  43. FILL_IN_BLANKS => array('fill_blanks.class.php' , 'FillBlanks'),
  44. MATCHING => array('matching.class.php' , 'Matching'),
  45. FREE_ANSWER => array('freeanswer.class.php' , 'FreeAnswer'),
  46. HOT_SPOT => array('hotspot.class.php' , 'HotSpot')
  47. );
  48. /**
  49. * constructor of the class
  50. *
  51. * @author - Olivier Brouckaert
  52. */
  53. function Question()
  54. {
  55. $this->id=0;
  56. $this->question='';
  57. $this->description='';
  58. $this->weighting=0;
  59. $this->position=1;
  60. $this->picture='';
  61. $this->level = 1;
  62. $this->exerciseList=array();
  63. }
  64. /**
  65. * reads question informations from the data base
  66. *
  67. * @author - Olivier Brouckaert
  68. * @param - integer $id - question ID
  69. * @return - boolean - true if question exists, otherwise false
  70. */
  71. static function read($id)
  72. {
  73. global $_course;
  74. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  75. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  76. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  77. $sql="SELECT question,description,ponderation,position,type,picture,level FROM $TBL_QUESTIONS WHERE id='".Database::escape_string($id)."'";
  78. $result=api_sql_query($sql,__FILE__,__LINE__);
  79. // if the question has been found
  80. if($object=mysql_fetch_object($result))
  81. {
  82. $objQuestion = Question::getInstance($object->type);
  83. $objQuestion->id=$id;
  84. $objQuestion->question=$object->question;
  85. $objQuestion->description=$object->description;
  86. $objQuestion->weighting=$object->ponderation;
  87. $objQuestion->position=$object->position;
  88. $objQuestion->type=$object->type;
  89. $objQuestion->picture=$object->picture;
  90. $objQuestion->level=(int) $object->level;
  91. $sql="SELECT exercice_id FROM $TBL_EXERCICE_QUESTION WHERE question_id='".intval($id)."'";
  92. $result=api_sql_query($sql,__FILE__,__LINE__);
  93. // fills the array with the exercises which this question is in
  94. while($object=mysql_fetch_object($result))
  95. {
  96. $objQuestion->exerciseList[]=$object->exercice_id;
  97. }
  98. return $objQuestion;
  99. }
  100. // question not found
  101. return false;
  102. }
  103. /**
  104. * returns the question ID
  105. *
  106. * @author - Olivier Brouckaert
  107. * @return - integer - question ID
  108. */
  109. function selectId()
  110. {
  111. return $this->id;
  112. }
  113. /**
  114. * returns the question title
  115. *
  116. * @author - Olivier Brouckaert
  117. * @return - string - question title
  118. */
  119. function selectTitle()
  120. {
  121. $this->question=api_parse_tex($this->question);
  122. return $this->question;
  123. }
  124. /**
  125. * returns the question description
  126. *
  127. * @author - Olivier Brouckaert
  128. * @return - string - question description
  129. */
  130. function selectDescription()
  131. {
  132. $this->description=api_parse_tex($this->description);
  133. return $this->description;
  134. }
  135. /**
  136. * returns the question weighting
  137. *
  138. * @author - Olivier Brouckaert
  139. * @return - integer - question weighting
  140. */
  141. function selectWeighting()
  142. {
  143. return $this->weighting;
  144. }
  145. /**
  146. * returns the question position
  147. *
  148. * @author - Olivier Brouckaert
  149. * @return - integer - question position
  150. */
  151. function selectPosition()
  152. {
  153. return $this->position;
  154. }
  155. /**
  156. * returns the answer type
  157. *
  158. * @author - Olivier Brouckaert
  159. * @return - integer - answer type
  160. */
  161. function selectType()
  162. {
  163. return $this->type;
  164. }
  165. /**
  166. * returns the level of the question
  167. *
  168. * @author - Nicolas Raynaud
  169. * @return - integer - level of the question, 0 by default.
  170. */
  171. function selectLevel()
  172. {
  173. return $this->level;
  174. }
  175. /**
  176. * returns the picture name
  177. *
  178. * @author - Olivier Brouckaert
  179. * @return - string - picture name
  180. */
  181. function selectPicture()
  182. {
  183. return $this->picture;
  184. }
  185. /**
  186. * returns the array with the exercise ID list
  187. *
  188. * @author - Olivier Brouckaert
  189. * @return - array - list of exercise ID which the question is in
  190. */
  191. function selectExerciseList()
  192. {
  193. return $this->exerciseList;
  194. }
  195. /**
  196. * returns the number of exercises which this question is in
  197. *
  198. * @author - Olivier Brouckaert
  199. * @return - integer - number of exercises
  200. */
  201. function selectNbrExercises()
  202. {
  203. return sizeof($this->exerciseList);
  204. }
  205. /**
  206. * changes the question title
  207. *
  208. * @author - Olivier Brouckaert
  209. * @param - string $title - question title
  210. */
  211. function updateTitle($title)
  212. {
  213. $this->question=$title;
  214. }
  215. /**
  216. * changes the question description
  217. *
  218. * @author - Olivier Brouckaert
  219. * @param - string $description - question description
  220. */
  221. function updateDescription($description)
  222. {
  223. $this->description=$description;
  224. }
  225. /**
  226. * changes the question weighting
  227. *
  228. * @author - Olivier Brouckaert
  229. * @param - integer $weighting - question weighting
  230. */
  231. function updateWeighting($weighting)
  232. {
  233. $this->weighting=$weighting;
  234. }
  235. /**
  236. * changes the question position
  237. *
  238. * @author - Olivier Brouckaert
  239. * @param - integer $position - question position
  240. */
  241. function updatePosition($position)
  242. {
  243. $this->position=$position;
  244. }
  245. /**
  246. * changes the question level
  247. *
  248. * @author - Nicolas Raynaud
  249. * @param - integer $level - question level
  250. */
  251. function updateLevel($level)
  252. {
  253. $this->level=$level;
  254. }
  255. /**
  256. * changes the answer type. If the user changes the type from "unique answer" to "multiple answers"
  257. * (or conversely) answers are not deleted, otherwise yes
  258. *
  259. * @author - Olivier Brouckaert
  260. * @param - integer $type - answer type
  261. */
  262. function updateType($type)
  263. {
  264. global $TBL_REPONSES;
  265. // if we really change the type
  266. if($type != $this->type)
  267. {
  268. // if we don't change from "unique answer" to "multiple answers" (or conversely)
  269. if(!in_array($this->type,array(UNIQUE_ANSWER,MULTIPLE_ANSWER)) || !in_array($type,array(UNIQUE_ANSWER,MULTIPLE_ANSWER)))
  270. {
  271. // removes old answers
  272. $sql="DELETE FROM $TBL_REPONSES WHERE question_id='".Database::escape_string($this->id)."'";
  273. api_sql_query($sql,__FILE__,__LINE__);
  274. }
  275. $this->type=$type;
  276. }
  277. }
  278. /**
  279. * adds a picture to the question
  280. *
  281. * @author - Olivier Brouckaert
  282. * @param - string $Picture - temporary path of the picture to upload
  283. * @param - string $PictureName - Name of the picture
  284. * @return - boolean - true if uploaded, otherwise false
  285. */
  286. function uploadPicture($Picture,$PictureName)
  287. {
  288. global $picturePath, $_course, $_user;
  289. if (!file_exists($picturePath)) {
  290. if (mkdir($picturePath)) {
  291. $perm = api_get_setting('permissions_for_new_directories');
  292. $perm = octdec(!empty($perm)?$perm:'0770');
  293. chmod($picturePath,$perm);
  294. // document path
  295. $documentPath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . "/document";
  296. $path = str_replace($documentPath,'',$picturePath);
  297. $title_path = basename($picturePath);
  298. $doc_id = add_document($_course, $path, 'folder', 0,$title_path);
  299. api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id']);
  300. }
  301. }
  302. // if the question has got an ID
  303. if($this->id)
  304. {
  305. $extension = pathinfo($PictureName, PATHINFO_EXTENSION);
  306. $this->picture='quiz-'.$this->id.'.jpg';
  307. if($extension == 'gif' || $extension == 'png')
  308. {
  309. $o_img = new image($Picture);
  310. $o_img->send_image('JPG',$picturePath.'/'.$this->picture);
  311. $document_id = add_document($_course, '/images/'.$this->picture, 'file', filesize($picturePath.'/'.$this->picture),$this->picture);
  312. }
  313. else
  314. {
  315. move_uploaded_file($Picture,$picturePath.'/'.$this->picture)?true:false;
  316. }
  317. $document_id = add_document($_course, '/images/'.$this->picture, 'file', filesize($picturePath.'/'.$this->picture),$this->picture);
  318. if($document_id)
  319. {
  320. return api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_user['user_id']);
  321. }
  322. }
  323. return false;
  324. }
  325. /**
  326. * Resizes a picture || Warning!: can only be called after uploadPicture, or if picture is already available in object.
  327. *
  328. * @author - Toon Keppens
  329. * @param - string $Dimension - Resizing happens proportional according to given dimension: height|width|any
  330. * @param - integer $Max - Maximum size
  331. * @return - boolean - true if success, false if failed
  332. */
  333. function resizePicture($Dimension, $Max)
  334. {
  335. global $picturePath;
  336. // if the question has an ID
  337. if($this->id)
  338. {
  339. // Get dimensions from current image.
  340. $current_img = imagecreatefromjpeg($picturePath.'/'.$this->picture);
  341. $current_image_size = getimagesize($picturePath.'/'.$this->picture);
  342. $current_height = imagesy($current_img);
  343. $current_width = imagesx($current_img);
  344. if($current_image_size[0] < $Max && $current_image_size[1] <$Max)
  345. return true;
  346. elseif($current_height == "")
  347. return false;
  348. // Resize according to height.
  349. if ($Dimension == "height")
  350. {
  351. $resize_scale = $current_height / $Max;
  352. $new_height = $Max;
  353. $new_width = ceil($current_width / $resize_scale);
  354. }
  355. // Resize according to width
  356. if ($Dimension == "width")
  357. {
  358. $resize_scale = $current_width / $Max;
  359. $new_width = $Max;
  360. $new_height = ceil($current_height / $resize_scale);
  361. }
  362. // Resize according to height or width, both should not be larger than $Max after resizing.
  363. if ($Dimension == "any")
  364. {
  365. if ($current_height > $current_width || $current_height == $current_width)
  366. {
  367. $resize_scale = $current_height / $Max;
  368. $new_height = $Max;
  369. $new_width = ceil($current_width / $resize_scale);
  370. }
  371. if ($current_height < $current_width)
  372. {
  373. $resize_scale = $current_width / $Max;
  374. $new_width = $Max;
  375. $new_height = ceil($current_height / $resize_scale);
  376. }
  377. }
  378. // Create new image
  379. $new_img = imagecreatetruecolor($new_width, $new_height);
  380. $bgColor = imagecolorallocate($new_img, 255,255,255);
  381. imagefill($new_img , 0,0 , $bgColor);
  382. // Resize image
  383. imagecopyresized($new_img, $current_img, 0, 0, 0, 0, $new_width, $new_height, $current_width, $current_height);
  384. // Write image to file
  385. $result = imagejpeg($new_img, $picturePath.'/'.$this->picture, 100);
  386. // Delete temperory images, clear memory
  387. imagedestroy($current_img);
  388. imagedestroy($new_img);
  389. if ($result)
  390. {
  391. return true;
  392. }
  393. else
  394. {
  395. return false;
  396. }
  397. }
  398. }
  399. /**
  400. * deletes the picture
  401. *
  402. * @author - Olivier Brouckaert
  403. * @return - boolean - true if removed, otherwise false
  404. */
  405. function removePicture()
  406. {
  407. global $picturePath;
  408. // if the question has got an ID and if the picture exists
  409. if($this->id)
  410. {
  411. $picture=$this->picture;
  412. $this->picture='';
  413. return @unlink($picturePath.'/'.$picture)?true:false;
  414. }
  415. return false;
  416. }
  417. /**
  418. * exports a picture to another question
  419. *
  420. * @author - Olivier Brouckaert
  421. * @param - integer $questionId - ID of the target question
  422. * @return - boolean - true if copied, otherwise false
  423. */
  424. function exportPicture($questionId)
  425. {
  426. global $TBL_QUESTIONS, $picturePath;
  427. // if the question has got an ID and if the picture exists
  428. if($this->id && !empty($this->picture))
  429. {
  430. $picture=explode('.',$this->picture);
  431. $Extension=$picture[sizeof($picture)-1];
  432. $picture='quiz-'.$questionId.'.'.$Extension;
  433. $sql="UPDATE $TBL_QUESTIONS SET picture='".Database::escape_string($picture)."' WHERE id='".Database::escape_string($questionId)."'";
  434. api_sql_query($sql,__FILE__,__LINE__);
  435. return @copy($picturePath.'/'.$this->picture,$picturePath.'/'.$picture)?true:false;
  436. }
  437. return false;
  438. }
  439. /**
  440. * saves the picture coming from POST into a temporary file
  441. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  442. * For example, if we first show a confirmation box.
  443. *
  444. * @author - Olivier Brouckaert
  445. * @param - string $Picture - temporary path of the picture to move
  446. * @param - string $PictureName - Name of the picture
  447. */
  448. function setTmpPicture($Picture,$PictureName)
  449. {
  450. global $picturePath;
  451. $PictureName=explode('.',$PictureName);
  452. $Extension=$PictureName[sizeof($PictureName)-1];
  453. // saves the picture into a temporary file
  454. @move_uploaded_file($Picture,$picturePath.'/tmp.'.$Extension);
  455. }
  456. /**
  457. * moves the temporary question "tmp" to "quiz-$questionId"
  458. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  459. * For example, if we first show a confirmation box.
  460. *
  461. * @author - Olivier Brouckaert
  462. * @return - boolean - true if moved, otherwise false
  463. */
  464. function getTmpPicture()
  465. {
  466. global $picturePath;
  467. // if the question has got an ID and if the picture exists
  468. if($this->id)
  469. {
  470. if(file_exists($picturePath.'/tmp.jpg'))
  471. {
  472. $Extension='jpg';
  473. }
  474. elseif(file_exists($picturePath.'/tmp.gif'))
  475. {
  476. $Extension='gif';
  477. }
  478. elseif(file_exists($picturePath.'/tmp.png'))
  479. {
  480. $Extension='png';
  481. }
  482. $this->picture='quiz-'.$this->id.'.'.$Extension;
  483. return @rename($picturePath.'/tmp.'.$Extension,$picturePath.'/'.$this->picture)?true:false;
  484. }
  485. return false;
  486. }
  487. /**
  488. * updates the question in the data base
  489. * if an exercise ID is provided, we add that exercise ID into the exercise list
  490. *
  491. * @author - Olivier Brouckaert
  492. * @param - integer $exerciseId - exercise ID if saving in an exercise
  493. */
  494. function save($exerciseId=0) {
  495. global $_course,$_user;
  496. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  497. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  498. $id=$this->id;
  499. $question=$this->question;
  500. $description=$this->description;
  501. $weighting=$this->weighting;
  502. $position=$this->position;
  503. $type=$this->type;
  504. $picture=$this->picture;
  505. $level=$this->level;
  506. // question already exists
  507. if(!empty($id)) {
  508. $sql="UPDATE $TBL_QUESTIONS SET
  509. question ='".Database::escape_string(Security::remove_XSS($question))."',
  510. description ='".Database::escape_string(Security::remove_XSS(api_html_entity_decode($description),COURSEMANAGERLOWSECURITY))."',
  511. ponderation ='".Database::escape_string($weighting)."',
  512. position ='".Database::escape_string($position)."',
  513. type ='".Database::escape_string($type)."',
  514. picture ='".Database::escape_string($picture)."',
  515. level ='".Database::escape_string($level)."'
  516. WHERE id='".Database::escape_string($id)."'";
  517. api_sql_query($sql,__FILE__,__LINE__);
  518. if(!empty($exerciseId)) {
  519. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizQuestionUpdated',$_user['user_id']);
  520. }
  521. if (api_get_setting('search_enabled')=='true') {
  522. if ($exerciseId != 0) {
  523. $this -> search_engine_edit($exerciseId);
  524. } else {
  525. /**
  526. * actually there is *not* an user interface for
  527. * creating questions without a relation with an exercise
  528. */
  529. }
  530. }
  531. } else {// creates a new question
  532. $sql="SELECT max(position) FROM $TBL_QUESTIONS as question, $TBL_EXERCICE_QUESTION as test_question WHERE question.id=test_question.question_id AND test_question.exercice_id='".Database::escape_string($exerciseId)."'";
  533. $result=api_sql_query($sql);
  534. $current_position=Database::result($result,0,0);
  535. $this -> updatePosition($current_position+1);
  536. $position = $this -> position;
  537. $sql="INSERT INTO $TBL_QUESTIONS(question,description,ponderation,position,type,picture,level) VALUES(
  538. '".Database::escape_string(Security::remove_XSS($question))."',
  539. '".Database::escape_string(Security::remove_XSS(api_html_entity_decode($description),COURSEMANAGERLOWSECURITY))."',
  540. '".Database::escape_string($weighting)."',
  541. '".Database::escape_string($position)."',
  542. '".Database::escape_string($type)."',
  543. '".Database::escape_string($picture)."',
  544. '".Database::escape_string($level)."'
  545. )";
  546. api_sql_query($sql,__FILE__,__LINE__);
  547. $this->id=Database::get_last_insert_id();
  548. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizQuestionAdded',$_user['user_id']);
  549. // If hotspot, create first answer
  550. if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) {
  551. $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
  552. $sql="INSERT INTO $TBL_ANSWERS (`id` , `question_id` , `answer` , `correct` , `comment` , `ponderation` , `position` , `hotspot_coordinates` , `hotspot_type` ) VALUES ('1', '".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'square')";
  553. api_sql_query($sql,__FILE__,__LINE__);
  554. }
  555. if (api_get_setting('search_enabled')=='true') {
  556. if ($exerciseId != 0) {
  557. $this -> search_engine_edit($exerciseId, TRUE);
  558. } else {
  559. /**
  560. * actually there is *not* an user interface for
  561. * creating questions without a relation with an exercise
  562. */
  563. }
  564. }
  565. }
  566. // if the question is created in an exercise
  567. if($exerciseId) {
  568. /*
  569. $sql = 'UPDATE '.Database::get_course_table(TABLE_LP_ITEM).'
  570. SET max_score = '.intval($weighting).'
  571. WHERE item_type = "'.TOOL_QUIZ.'"
  572. AND path='.intval($exerciseId);
  573. api_sql_query($sql,__FILE__,__LINE__);
  574. */
  575. // adds the exercise into the exercise list of this question
  576. $this->addToList($exerciseId, TRUE);
  577. }
  578. }
  579. function search_engine_edit($exerciseId, $addQs=FALSE, $rmQs=FALSE) {
  580. // update search engine and its values table if enabled
  581. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  582. $course_id = api_get_course_id();
  583. // get search_did
  584. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  585. if ($addQs || $rmQs) {
  586. //there's only one row per question on normal db and one document per question on search engine db
  587. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
  588. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  589. } else {
  590. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%s LIMIT 1';
  591. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  592. }
  593. $res = api_sql_query($sql, __FILE__, __LINE__);
  594. if (Database::num_rows($res) > 0 || $addQs) {
  595. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  596. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  597. $di = new DokeosIndexer();
  598. if ($addQs) {
  599. $question_exercises = array((int)$exerciseId);
  600. } else {
  601. $question_exercises = array();
  602. }
  603. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  604. $di->connectDb(NULL, NULL, $lang);
  605. // retrieve others exercise ids
  606. $se_ref = Database::fetch_array($res);
  607. $se_doc = $di->get_document((int)$se_ref['search_did']);
  608. if ($se_doc !== FALSE) {
  609. if ( ($se_doc_data=$di->get_document_data($se_doc)) !== FALSE ) {
  610. $se_doc_data = unserialize($se_doc_data);
  611. if (isset($se_doc_data[SE_DATA]['type']) && $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION) {
  612. if (isset($se_doc_data[SE_DATA]['exercise_ids']) && is_array($se_doc_data[SE_DATA]['exercise_ids'])) {
  613. foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
  614. if (!in_array($old_value, $question_exercises)) {
  615. $question_exercises[] = $old_value;
  616. }
  617. }
  618. }
  619. }
  620. }
  621. }
  622. if ($rmQs) {
  623. while ( ($key=array_search($exerciseId, $question_exercises)) !== FALSE) {
  624. unset($question_exercises[$key]);
  625. }
  626. }
  627. // build the chunk to index
  628. $ic_slide = new IndexableChunk();
  629. $ic_slide->addValue("title", $this->question);
  630. $ic_slide->addCourseId($course_id);
  631. $ic_slide->addToolId(TOOL_QUIZ);
  632. $xapian_data = array(
  633. SE_COURSE_ID => $course_id,
  634. SE_TOOL_ID => TOOL_QUIZ,
  635. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_QUESTION, 'exercise_ids' => $question_exercises, 'question_id' => (int)$this->id),
  636. SE_USER => (int)api_get_user_id(),
  637. );
  638. $ic_slide->xapian_data = serialize($xapian_data);
  639. $ic_slide->addValue("content", $this->description);
  640. //TODO: index answers, see also form validation on question_admin.inc.php
  641. $di->remove_document((int)$se_ref['search_did']);
  642. $di->addChunk($ic_slide);
  643. //index and return search engine document id
  644. if (!empty($question_exercises)) { // if empty there is nothing to index
  645. $did = $di->index();
  646. unset($di);
  647. }
  648. if ($did || $rmQs) {
  649. // save it to db
  650. if ($addQs || $rmQs) {
  651. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=\'%s\'';
  652. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  653. } else {
  654. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\' AND ref_id_second_level=\'%s\'';
  655. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  656. }
  657. api_sql_query($sql,__FILE__,__LINE__);
  658. if ($rmQs) {
  659. if (!empty($question_exercises)) {
  660. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  661. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  662. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, array_shift($question_exercises), $this->id, $did);
  663. api_sql_query($sql,__FILE__,__LINE__);
  664. }
  665. } else {
  666. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  667. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  668. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
  669. api_sql_query($sql,__FILE__,__LINE__);
  670. }
  671. }
  672. }
  673. }
  674. }
  675. /**
  676. * adds an exercise into the exercise list
  677. *
  678. * @author - Olivier Brouckaert
  679. * @param - integer $exerciseId - exercise ID
  680. * @param - boolean $fromSave - comming from $this->save() or not
  681. */
  682. function addToList($exerciseId, $fromSave=FALSE) {
  683. global $TBL_EXERCICE_QUESTION;
  684. $id=$this->id;
  685. // checks if the exercise ID is not in the list
  686. if(!in_array($exerciseId,$this->exerciseList)) {
  687. $this->exerciseList[]=$exerciseId;
  688. $sql="INSERT INTO $TBL_EXERCICE_QUESTION (question_id, exercice_id) VALUES('".Database::escape_string($id)."','".Database::escape_string($exerciseId)."')";
  689. api_sql_query($sql,__FILE__,__LINE__);
  690. // we do not want to reindex if we had just saved adnd indexed the question
  691. if (!$fromSave) {
  692. $this->search_engine_edit($exerciseId, TRUE);
  693. }
  694. }
  695. }
  696. /**
  697. * removes an exercise from the exercise list
  698. *
  699. * @author - Olivier Brouckaert
  700. * @param - integer $exerciseId - exercise ID
  701. * @return - boolean - true if removed, otherwise false
  702. */
  703. function removeFromList($exerciseId) {
  704. global $TBL_EXERCICE_QUESTION;
  705. $id=$this->id;
  706. // searches the position of the exercise ID in the list
  707. $pos=array_search($exerciseId,$this->exerciseList);
  708. // exercise not found
  709. if($pos === false) {
  710. return false;
  711. } else {
  712. // deletes the position in the array containing the wanted exercise ID
  713. unset($this->exerciseList[$pos]);
  714. //update order of other elements
  715. $sql = "SELECT question_order FROM $TBL_EXERCICE_QUESTION WHERE question_id='".Database::escape_string($id)."' AND exercice_id='".Database::escape_string($exerciseId)."'";
  716. $res = api_sql_query($sql,__FILE__,__LINE__);
  717. if (Database::num_rows($res)>0) {
  718. $row = Database::fetch_array($res);
  719. if (!empty($row['question_order'])) {
  720. $sql = "UPDATE $TBL_EXERCICE_QUESTION SET question_order = question_order-1 WHERE exercice_id='".Database::escape_string($exerciseId)."' AND question_order > ".$row['question_order'];
  721. $res = api_sql_query($sql,__FILE__,__LINE__);
  722. }
  723. }
  724. $sql="DELETE FROM $TBL_EXERCICE_QUESTION WHERE question_id='".Database::escape_string($id)."' AND exercice_id='".Database::escape_string($exerciseId)."'";
  725. api_sql_query($sql,__FILE__,__LINE__);
  726. return true;
  727. }
  728. }
  729. /**
  730. * deletes a question from the database
  731. * the parameter tells if the question is removed from all exercises (value = 0),
  732. * or just from one exercise (value = exercise ID)
  733. *
  734. * @author - Olivier Brouckaert
  735. * @param - integer $deleteFromEx - exercise ID if the question is only removed from one exercise
  736. */
  737. function delete($deleteFromEx=0) {
  738. global $_course,$_user;
  739. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  740. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  741. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  742. $id=$this->id;
  743. // if the question must be removed from all exercises
  744. if(!$deleteFromEx)
  745. {
  746. //update the question_order of each question to avoid inconsistencies
  747. $sql = "SELECT exercice_id, question_order FROM $TBL_EXERCICE_QUESTION WHERE question_id='".Database::escape_string($id)."'";
  748. $res = api_sql_query($sql,__FILE__,__LINE__);
  749. if (Database::num_rows($res)>0) {
  750. while ($row = Database::fetch_array($res)) {
  751. if (!empty($row['question_order'])) {
  752. $sql = "UPDATE $TBL_EXERCICE_QUESTION SET question_order = question_order-1 WHERE exercice_id='".Database::escape_string($row['exercice_id'])."' AND question_order > ".$row['question_order'];
  753. $res = api_sql_query($sql,__FILE__,__LINE__);
  754. }
  755. }
  756. }
  757. $sql="DELETE FROM $TBL_EXERCICE_QUESTION WHERE question_id='".Database::escape_string($id)."'";
  758. api_sql_query($sql,__FILE__,__LINE__);
  759. $sql="DELETE FROM $TBL_QUESTIONS WHERE id='".Database::escape_string($id)."'";
  760. api_sql_query($sql,__FILE__,__LINE__);
  761. $sql="DELETE FROM $TBL_REPONSES WHERE question_id='".Database::escape_string($id)."'";
  762. api_sql_query($sql,__FILE__,__LINE__);
  763. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizQuestionDeleted',$_user['user_id']);
  764. $this->removePicture();
  765. // resets the object
  766. $this->Question();
  767. }
  768. // just removes the exercise from the list
  769. else
  770. {
  771. $this->removeFromList($deleteFromEx);
  772. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  773. // disassociate question with this exercise
  774. $this -> search_engine_edit($deleteFromEx, FALSE, TRUE);
  775. }
  776. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizQuestionDeleted',$_user['user_id']);
  777. }
  778. }
  779. /**
  780. * duplicates the question
  781. *
  782. * @author - Olivier Brouckaert
  783. * @return - integer - ID of the new question
  784. */
  785. function duplicate() {
  786. global $TBL_QUESTIONS, $picturePath;
  787. $question=$this->question;
  788. $description=$this->description;
  789. $weighting=$this->weighting;
  790. $position=$this->position;
  791. $type=$this->type;
  792. $sql="INSERT INTO $TBL_QUESTIONS(question,description,ponderation,position,type) VALUES('".Database::escape_string($question)."','".Database::escape_string($description)."','".Database::escape_string($weighting)."','".Database::escape_string($position)."','".Database::escape_string($type)."')";
  793. api_sql_query($sql,__FILE__,__LINE__);
  794. $id=Database::get_last_insert_id();
  795. // duplicates the picture
  796. $this->exportPicture($id);
  797. return $id;
  798. }
  799. /**
  800. * Returns an instance of the class corresponding to the type
  801. * @param integer $type the type of the question
  802. * @return an instance of a Question subclass (or of Questionc class by default)
  803. */
  804. static function getInstance ($type) {
  805. if (!is_null($type)) {
  806. list($file_name,$class_name) = self::$questionTypes[$type];
  807. include_once($file_name);
  808. if (class_exists($class_name)) {
  809. return new $class_name();
  810. } else {
  811. echo 'Can\'t instanciate class '.$class_name.' of type '.$type;
  812. return null;
  813. }
  814. }
  815. }
  816. /**
  817. * Creates the form to create / edit a question
  818. * A subclass can redifine this function to add fields...
  819. * @param FormValidator $form the formvalidator instance (by reference)
  820. */
  821. function createForm (&$form,$fck_config=0)
  822. {
  823. echo ' <style>
  824. div.row div.label{ width: 10%; }
  825. div.row div.formw{ width: 89%; }
  826. .media { display:none;}
  827. </style>';
  828. echo '<script>
  829. // hack to hide http://cksource.com/forums/viewtopic.php?f=6&t=8700
  830. function FCKeditor_OnComplete( editorInstance )
  831. {
  832. if (document.getElementById ( \'HiddenFCK\' + editorInstance.Name )) {
  833. HideFCKEditorByInstanceName (editorInstance.Name);
  834. }
  835. }
  836. function HideFCKEditorByInstanceName ( editorInstanceName ) {
  837. if (document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className == "HideFCKEditor" ) {
  838. document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className = "media";
  839. }
  840. }
  841. function show_media()
  842. {
  843. var my_display = document.getElementById(\'HiddenFCKquestionDescription\').style.display;
  844. if(my_display== \'none\' || my_display == \'\') {
  845. document.getElementById(\'HiddenFCKquestionDescription\').style.display = \'block\';
  846. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;<img style="vertical-align: middle;" src="../img/looknfeelna.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'\';
  847. } else {
  848. document.getElementById(\'HiddenFCKquestionDescription\').style.display = \'none\';
  849. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;<img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'\';
  850. }
  851. }
  852. </script>';
  853. $renderer = $form->defaultRenderer();
  854. $form->addElement('html','<div class="form">');
  855. // question name
  856. $form->addElement('text','questionName','<span class="form_required">*</span> '.get_lang('Question'),'size="80"');
  857. //$form->applyFilter('questionName','html_filter');
  858. //$radios_results_enabled[] = $form->createElement('static', null, null, null);
  859. //$test=FormValidator :: createElement ('text', 'questionName');
  860. //$radios_results_enabled[]=$test;
  861. // question level
  862. $select_level = array (1,2,3,4,5);
  863. //$radios_results_enabled[] =
  864. foreach($select_level as $val) {
  865. $radios_results_enabled[] = FormValidator :: createElement ('radio', null, null,$val,$val);
  866. }
  867. $form->addGroup($radios_results_enabled,'questionLevel',get_lang('Difficulty'));
  868. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw" >{element}</div></div>','questionName');
  869. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>','questionLevel');
  870. $form->addRule('questionName', get_lang('GiveQuestion'), 'required');
  871. // question type
  872. $answerType= intval($_REQUEST['answerType']);
  873. $form->addElement('hidden','answerType',$_REQUEST['answerType']);
  874. // html editor
  875. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  876. if(is_array($fck_config)){
  877. $editor_config = array_merge($editor_config, $fck_config);
  878. }
  879. if(!api_is_allowed_to_edit()) $editor_config['UserStatus'] = 'student';
  880. $form -> addElement('html','<div class="row">
  881. <div class="label"></div>
  882. <div class="formw" style="height:50px">
  883. <a href="javascript://" onclick=" return show_media()"> <span id="media_icon"> <img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'</span></a>
  884. </div>
  885. </div>');
  886. $form -> addElement ('html','<div class="HideFCKEditor" id="HiddenFCKquestionDescription" >');
  887. $form->add_html_editor('questionDescription', get_lang('langQuestionDescription'), false, false, $editor_config);
  888. $form -> addElement ('html','</div>');
  889. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>','questionDescription');
  890. // hidden values
  891. $form->addElement('hidden','myid',$_REQUEST['myid']);
  892. switch($answerType) {
  893. case 1: $this->question = get_lang('langDefaultUniqueQuestion'); break;
  894. case 2: $this->question = get_lang('langDefaultMultipleQuestion'); break;
  895. case 3: $this->question = get_lang('langDefaultFillBlankQuestion'); break;
  896. case 4: $this->question = get_lang('langDefaultMathingQuestion'); break;
  897. case 5: $this->question = get_lang('langDefaultOpenQuestion'); break;
  898. }
  899. $form->addElement('html','</div>');
  900. // default values
  901. $defaults = array();
  902. $defaults['questionName'] = $this -> question;
  903. $defaults['questionDescription'] = $this -> description;
  904. $defaults['questionLevel'] = $this -> level;
  905. $form -> setDefaults($defaults);
  906. }
  907. /**
  908. * function which process the creation of questions
  909. * @param FormValidator $form the formvalidator instance
  910. * @param Exercise $objExercise the Exercise instance
  911. */
  912. function processCreation ($form, $objExercise) {
  913. $this -> updateTitle($form->getSubmitValue('questionName'));
  914. $this -> updateDescription($form->getSubmitValue('questionDescription'));
  915. $this -> updateLevel($form->getSubmitValue('questionLevel'));
  916. $this -> save($objExercise -> id);
  917. // modify the exercise
  918. $objExercise->addToList($this -> id);
  919. $objExercise->update_question_positions();
  920. }
  921. /**
  922. * abstract function which creates the form to create / edit the answers of the question
  923. * @param the formvalidator instance
  924. */
  925. abstract function createAnswersForm ($form);
  926. /**
  927. * abstract function which process the creation of answers
  928. * @param the formvalidator instance
  929. */
  930. abstract function processAnswersCreation ($form);
  931. /**
  932. * Displays the menu of question types
  933. */
  934. static function display_type_menu ($feedbacktype = 0)
  935. {
  936. global $exerciseId;
  937. // 1. by default we show all the question types
  938. $question_type_custom_list = self::$questionTypes;
  939. if (!isset($feedbacktype)) $feedbacktype=0;
  940. if ($feedbacktype==1) {
  941. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  942. $question_type_custom_list = array ( UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER]);
  943. }
  944. echo '<ul class="question_menu" style="padding:0px; margin:-2px;">';
  945. foreach ($question_type_custom_list as $i=>$a_type) {
  946. // include the class of the type
  947. include_once($a_type[0]);
  948. // get the picture of the type and the langvar which describes it
  949. eval('$img = '.$a_type[1].'::$typePicture;');
  950. eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
  951. echo '<li>';
  952. echo '<div class="icon_image_content">';
  953. echo '<a href="admin.php?newQuestion=yes&answerType='.$i.'">'.Display::return_icon($img, $explanation).'</a>';
  954. echo '<br>';
  955. echo '<a href="admin.php?newQuestion=yes&answerType='.$i.'">'.$explanation.'</a>';
  956. echo '</div>';
  957. echo '</li>';
  958. }
  959. echo '<li>';
  960. echo '<div class="icon_image_content">';
  961. if ($feedbacktype==1) {
  962. echo $url = '<a href="question_pool.php?type=1&fromExercise='.$exerciseId.'">';
  963. } else {
  964. echo $url = '<a href="question_pool.php?fromExercise='.$exerciseId.'">';
  965. }
  966. echo Display::return_icon('database.png', get_lang('GetExistingQuestion'), '');
  967. echo '</a><br>';
  968. echo $url;
  969. echo get_lang('GetExistingQuestion');
  970. echo '</a>';
  971. echo '</div></li>';
  972. echo '</ul>';
  973. }
  974. static function get_types_information()
  975. {
  976. return self::$questionTypes;
  977. }
  978. }
  979. endif;
  980. ?>