question.class.php 37 KB

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