question.class.php 38 KB

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