question.class.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. <?php // $Id: question.class.php 20224 2009-04-30 15:59:43Z cfasanando $
  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 20224 2009-04-30 15:59:43Z cfasanando $
  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. {
  500. global $_course,$_user;
  501. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  502. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  503. $id=$this->id;
  504. $question=addslashes($this->question);
  505. $description=addslashes($this->description);
  506. $weighting=$this->weighting;
  507. $position=$this->position;
  508. $type=$this->type;
  509. $picture=addslashes($this->picture);
  510. $level=$this->level;
  511. // question already exists
  512. if(!empty($id))
  513. {
  514. $sql="UPDATE $TBL_QUESTIONS SET
  515. question ='".Database::escape_string($question)."',
  516. description ='".Database::escape_string($description)."',
  517. ponderation ='".Database::escape_string($weighting)."',
  518. position ='".Database::escape_string($position)."',
  519. type ='".Database::escape_string($type)."',
  520. picture ='".Database::escape_string($picture)."',
  521. level ='".Database::escape_string($level)."'
  522. WHERE id='".Database::escape_string($id)."'";
  523. api_sql_query($sql,__FILE__,__LINE__);
  524. if(!empty($exerciseId)) {
  525. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizQuestionUpdated',$_user['user_id']);
  526. }
  527. if (api_get_setting('search_enabled')=='true') {
  528. if ($exerciseId != 0) {
  529. $this -> search_engine_edit($exerciseId);
  530. }
  531. else {
  532. /**
  533. * actually there is *not* an user interface for
  534. * creating questions without a relation with an exercise
  535. */
  536. }
  537. }
  538. }
  539. // creates a new question
  540. else
  541. {
  542. $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)."'";
  543. $result=api_sql_query($sql);
  544. $current_position=Database::result($result,0,0);
  545. $this -> updatePosition($current_position+1);
  546. $position = $this -> position;
  547. $sql="INSERT INTO $TBL_QUESTIONS(question,description,ponderation,position,type,picture,level) VALUES(
  548. '".Database::escape_string($question)."',
  549. '".Database::escape_string($description)."',
  550. '".Database::escape_string($weighting)."',
  551. '".Database::escape_string($position)."',
  552. '".Database::escape_string($type)."',
  553. '".Database::escape_string($picture)."',
  554. '".Database::escape_string($level)."'
  555. )";
  556. api_sql_query($sql,__FILE__,__LINE__);
  557. $this->id=Database::get_last_insert_id();
  558. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizQuestionAdded',$_user['user_id']);
  559. // If hotspot, create first answer
  560. if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) {
  561. $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
  562. $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')";
  563. api_sql_query($sql,__FILE__,__LINE__);
  564. }
  565. if (api_get_setting('search_enabled')=='true') {
  566. if ($exerciseId != 0) {
  567. $this -> search_engine_edit($exerciseId, TRUE);
  568. }
  569. else {
  570. /**
  571. * actually there is *not* an user interface for
  572. * creating questions without a relation with an exercise
  573. */
  574. }
  575. }
  576. }
  577. // if the question is created in an exercise
  578. if($exerciseId)
  579. {
  580. $sql = 'UPDATE '.Database::get_course_table(TABLE_LP_ITEM).'
  581. SET max_score = '.intval($weighting).'
  582. WHERE item_type = "'.TOOL_QUIZ.'"
  583. AND path='.intval($exerciseId);
  584. api_sql_query($sql,__FILE__,__LINE__);
  585. // adds the exercise into the exercise list of this question
  586. $this->addToList($exerciseId, TRUE);
  587. }
  588. }
  589. function search_engine_edit($exerciseId, $addQs=FALSE, $rmQs=FALSE) {
  590. // update search engine and its values table if enabled
  591. if (api_get_setting('search_enabled')=='true') {
  592. $course_id = api_get_course_id();
  593. // get search_did
  594. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  595. if ($addQs || $rmQs) {
  596. //there's only one row per question on normal db and one document per question on search engine db
  597. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
  598. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  599. }
  600. else {
  601. $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';
  602. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  603. }
  604. $res = api_sql_query($sql, __FILE__, __LINE__);
  605. if (Database::num_rows($res) > 0 || $addQs) {
  606. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  607. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  608. $di = new DokeosIndexer();
  609. if ($addQs) {
  610. $question_exercises = array((int)$exerciseId);
  611. }
  612. else {
  613. $question_exercises = array();
  614. }
  615. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  616. $di->connectDb(NULL, NULL, $lang);
  617. // retrieve others exercise ids
  618. $se_ref = Database::fetch_array($res);
  619. $se_doc = $di->get_document((int)$se_ref['search_did']);
  620. if ($se_doc !== FALSE) {
  621. if ( ($se_doc_data=$di->get_document_data($se_doc)) !== FALSE ) {
  622. $se_doc_data = unserialize($se_doc_data);
  623. if (isset($se_doc_data[SE_DATA]['type']) && $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION) {
  624. if (isset($se_doc_data[SE_DATA]['exercise_ids']) && is_array($se_doc_data[SE_DATA]['exercise_ids'])) {
  625. foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
  626. if (!in_array($old_value, $question_exercises)) {
  627. $question_exercises[] = $old_value;
  628. }
  629. }
  630. }
  631. }
  632. }
  633. }
  634. if ($rmQs) {
  635. while ( ($key=array_search($exerciseId, $question_exercises)) !== FALSE) {
  636. unset($question_exercises[$key]);
  637. }
  638. }
  639. // build the chunk to index
  640. $ic_slide = new IndexableChunk();
  641. $ic_slide->addValue("title", $this->question);
  642. $ic_slide->addCourseId($course_id);
  643. $ic_slide->addToolId(TOOL_QUIZ);
  644. $xapian_data = array(
  645. SE_COURSE_ID => $course_id,
  646. SE_TOOL_ID => TOOL_QUIZ,
  647. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_QUESTION, 'exercise_ids' => $question_exercises, 'question_id' => (int)$this->id),
  648. SE_USER => (int)api_get_user_id(),
  649. );
  650. $ic_slide->xapian_data = serialize($xapian_data);
  651. $ic_slide->addValue("content", $this->description);
  652. //TODO: index answers, see also form validation on question_admin.inc.php
  653. $di->remove_document((int)$se_ref['search_did']);
  654. $di->addChunk($ic_slide);
  655. //index and return search engine document id
  656. if (!empty($question_exercises)) { // if empty there is nothing to index
  657. $did = $di->index();
  658. unset($di);
  659. }
  660. if ($did || $rmQs) {
  661. // save it to db
  662. if ($addQs || $rmQs) {
  663. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=\'%s\'';
  664. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  665. }
  666. else {
  667. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\' AND ref_id_second_level=\'%s\'';
  668. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  669. }
  670. api_sql_query($sql,__FILE__,__LINE__);
  671. if ($rmQs) {
  672. if (!empty($question_exercises)) {
  673. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  674. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  675. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, array_shift($question_exercises), $this->id, $did);
  676. api_sql_query($sql,__FILE__,__LINE__);
  677. }
  678. }
  679. else {
  680. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  681. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  682. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
  683. api_sql_query($sql,__FILE__,__LINE__);
  684. }
  685. }
  686. }
  687. }
  688. }
  689. /**
  690. * adds an exercise into the exercise list
  691. *
  692. * @author - Olivier Brouckaert
  693. * @param - integer $exerciseId - exercise ID
  694. * @param - boolean $fromSave - comming from $this->save() or not
  695. */
  696. function addToList($exerciseId, $fromSave=FALSE)
  697. {
  698. global $TBL_EXERCICE_QUESTION;
  699. $id=$this->id;
  700. // checks if the exercise ID is not in the list
  701. if(!in_array($exerciseId,$this->exerciseList)) {
  702. $this->exerciseList[]=$exerciseId;
  703. $sql="INSERT INTO $TBL_EXERCICE_QUESTION (question_id, exercice_id) VALUES('".Database::escape_string($id)."','".Database::escape_string($exerciseId)."')";
  704. api_sql_query($sql,__FILE__,__LINE__);
  705. // we do not want to reindex if we had just saved adnd indexed the question
  706. if (!$fromSave) {
  707. $this->search_engine_edit($exerciseId, TRUE);
  708. }
  709. }
  710. }
  711. /**
  712. * removes an exercise from the exercise list
  713. *
  714. * @author - Olivier Brouckaert
  715. * @param - integer $exerciseId - exercise ID
  716. * @return - boolean - true if removed, otherwise false
  717. */
  718. function removeFromList($exerciseId)
  719. {
  720. global $TBL_EXERCICE_QUESTION;
  721. $id=$this->id;
  722. // searches the position of the exercise ID in the list
  723. $pos=array_search($exerciseId,$this->exerciseList);
  724. // exercise not found
  725. if($pos === false)
  726. {
  727. return false;
  728. }
  729. else
  730. {
  731. // deletes the position in the array containing the wanted exercise ID
  732. unset($this->exerciseList[$pos]);
  733. //update order of other elements
  734. $sql = "SELECT question_order FROM $TBL_EXERCICE_QUESTION WHERE question_id='".Database::escape_string($id)."' AND exercice_id='".Database::escape_string($exerciseId)."'";
  735. $res = api_sql_query($sql,__FILE__,__LINE__);
  736. if (Database::num_rows($res)>0) {
  737. $row = Database::fetch_array($res);
  738. if (!empty($row['question_order'])) {
  739. $sql = "UPDATE $TBL_EXERCICE_QUESTION SET question_order = question_order-1 WHERE exercice_id='".Database::escape_string($exerciseId)."' AND question_order > ".$row['question_order'];
  740. $res = api_sql_query($sql,__FILE__,__LINE__);
  741. }
  742. }
  743. $sql="DELETE FROM $TBL_EXERCICE_QUESTION WHERE question_id='".Database::escape_string($id)."' AND exercice_id='".Database::escape_string($exerciseId)."'";
  744. api_sql_query($sql,__FILE__,__LINE__);
  745. return true;
  746. }
  747. }
  748. /**
  749. * deletes a question from the database
  750. * the parameter tells if the question is removed from all exercises (value = 0),
  751. * or just from one exercise (value = exercise ID)
  752. *
  753. * @author - Olivier Brouckaert
  754. * @param - integer $deleteFromEx - exercise ID if the question is only removed from one exercise
  755. */
  756. function delete($deleteFromEx=0)
  757. {
  758. global $_course,$_user;
  759. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  760. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  761. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  762. $id=$this->id;
  763. // if the question must be removed from all exercises
  764. if(!$deleteFromEx)
  765. {
  766. //update the question_order of each question to avoid inconsistencies
  767. $sql = "SELECT exercice_id, question_order FROM $TBL_EXERCICE_QUESTION WHERE question_id='".Database::escape_string($id)."'";
  768. $res = api_sql_query($sql,__FILE__,__LINE__);
  769. if (Database::num_rows($res)>0) {
  770. while ($row = Database::fetch_array($res)) {
  771. if (!empty($row['question_order'])) {
  772. $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'];
  773. $res = api_sql_query($sql,__FILE__,__LINE__);
  774. }
  775. }
  776. }
  777. $sql="DELETE FROM $TBL_EXERCICE_QUESTION WHERE question_id='".Database::escape_string($id)."'";
  778. api_sql_query($sql,__FILE__,__LINE__);
  779. $sql="DELETE FROM $TBL_QUESTIONS WHERE id='".Database::escape_string($id)."'";
  780. api_sql_query($sql,__FILE__,__LINE__);
  781. $sql="DELETE FROM $TBL_REPONSES WHERE question_id='".Database::escape_string($id)."'";
  782. api_sql_query($sql,__FILE__,__LINE__);
  783. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizQuestionDeleted',$_user['user_id']);
  784. $this->removePicture();
  785. // resets the object
  786. $this->Question();
  787. }
  788. // just removes the exercise from the list
  789. else
  790. {
  791. $this->removeFromList($deleteFromEx);
  792. if (api_get_setting('search_enabled')=='true') {
  793. // disassociate question with this exercise
  794. $this -> search_engine_edit($deleteFromEx, FALSE, TRUE);
  795. }
  796. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizQuestionDeleted',$_user['user_id']);
  797. }
  798. }
  799. /**
  800. * duplicates the question
  801. *
  802. * @author - Olivier Brouckaert
  803. * @return - integer - ID of the new question
  804. */
  805. function duplicate() {
  806. global $TBL_QUESTIONS, $picturePath;
  807. $question=addslashes($this->question);
  808. $description=addslashes($this->description);
  809. $weighting=$this->weighting;
  810. $position=$this->position;
  811. $type=$this->type;
  812. $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)."')";
  813. api_sql_query($sql,__FILE__,__LINE__);
  814. $id=Database::get_last_insert_id();
  815. // duplicates the picture
  816. $this->exportPicture($id);
  817. return $id;
  818. }
  819. /**
  820. * Returns an instance of the class corresponding to the type
  821. * @param integer $type the type of the question
  822. * @return an instance of a Question subclass (or of Questionc class by default)
  823. */
  824. static function getInstance ($type) {
  825. if (!is_null($type)) {
  826. list($file_name,$class_name) = self::$questionTypes[$type];
  827. include_once($file_name);
  828. if (class_exists($class_name)) {
  829. return new $class_name();
  830. } else {
  831. echo 'Can\'t instanciate class '.$class_name.' of type '.$type;
  832. return null;
  833. }
  834. }
  835. }
  836. /**
  837. * Creates the form to create / edit a question
  838. * A subclass can redifine this function to add fields...
  839. * @param FormValidator $form the formvalidator instance (by reference)
  840. */
  841. function createForm (&$form,$fck_config=0)
  842. {
  843. echo ' <style>
  844. div.row div.label{ width: 10%; }
  845. div.row div.formw{ width: 89%; }
  846. </style>';
  847. echo '<script>
  848. function show_media()
  849. {
  850. if(document.getElementById(\'media\').style.display == \'none\') {
  851. document.getElementById(\'media\').style.display = \'block\';
  852. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;<img src="../img/looknfeelna.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'\';
  853. } else {
  854. document.getElementById(\'media\').style.display = \'none\';
  855. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;<img src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'\';
  856. }
  857. }
  858. </script>';
  859. $renderer = $form->defaultRenderer();
  860. $form->addElement('html','<div class="form">');
  861. // question name
  862. $form->addElement('text','questionName','<span class="form_required">*</span> '.get_lang('Question'),'size="60"');
  863. $form->applyFilter('questionName','html_filter');
  864. //$radios_results_enabled[] = $form->createElement('static', null, null, null);
  865. //$test=FormValidator :: createElement ('text', 'questionName');
  866. //$radios_results_enabled[]=$test;
  867. // question level
  868. $select_level = array (1,2,3,4,5);
  869. //$radios_results_enabled[] =
  870. foreach($select_level as $val) {
  871. $radios_results_enabled[] = FormValidator :: createElement ('radio', null, null,$val,$val);
  872. }
  873. $form->addGroup($radios_results_enabled,'questionLevel',get_lang('Difficulty'));
  874. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw" >{element}</div></div>','questionName');
  875. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>','questionLevel');
  876. $form->addRule('questionName', get_lang('GiveQuestion'), 'required');
  877. // question type
  878. $answerType= intval($_REQUEST['answerType']);
  879. $form->addElement('hidden','answerType',$_REQUEST['answerType']);
  880. // html editor
  881. global $fck_attribute;
  882. $fck_attribute = array();
  883. $fck_attribute['Width'] = '100%';
  884. $fck_attribute['Height'] = '150px';
  885. $fck_attribute['ToolbarSet'] = 'QuestionDescription';
  886. if(is_array($fck_config)){
  887. $fck_attribute = array_merge($fck_attribute,$fck_config);
  888. }
  889. if(!api_is_allowed_to_edit()) $fck_attribute['Config']['UserStatus'] = 'student';
  890. $form -> addElement('html','<div class="row">
  891. <div class="label"></div>
  892. <div class="formw" style="height:50px">
  893. <a href="javascript://" onclick=" return show_media()"> <span id="media_icon"> <img src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'</span></a>
  894. </div>
  895. </div>');
  896. $form -> addElement ('html','<div id="media" style="display:none;">');
  897. $form->add_html_editor('questionDescription', get_lang('langQuestionDescription'), false);
  898. $form -> addElement ('html','</div>');
  899. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>','questionDescription');
  900. // hidden values
  901. $form->addElement('hidden','myid',$_REQUEST['myid']);
  902. switch($answerType) {
  903. case 1: $this->question = get_lang('langDefaultUniqueQuestion'); break;
  904. case 2: $this->question = get_lang('langDefaultMultipleQuestion'); break;
  905. case 3: $this->question = get_lang('langDefaultFillBlankQuestion'); break;
  906. case 4: $this->question = get_lang('langDefaultMathingQuestion'); break;
  907. case 5: $this->question = get_lang('langDefaultOpenQuestion'); break;
  908. }
  909. // default values
  910. $defaults = array();
  911. $defaults['questionName'] = $this -> question;
  912. $defaults['questionDescription'] = $this -> description;
  913. $defaults['questionLevel'] = $this -> level;
  914. $form -> setDefaults($defaults);
  915. }
  916. /**
  917. * function which process the creation of questions
  918. * @param FormValidator $form the formvalidator instance
  919. * @param Exercise $objExercise the Exercise instance
  920. */
  921. function processCreation ($form, $objExercise) {
  922. $this -> updateTitle($form->getSubmitValue('questionName'));
  923. $this -> updateDescription($form->getSubmitValue('questionDescription'));
  924. $this -> updateLevel($form->getSubmitValue('questionLevel'));
  925. $this -> save($objExercise -> id);
  926. // modify the exercise
  927. $objExercise->addToList($this -> id);
  928. $objExercise->update_question_positions();
  929. }
  930. /**
  931. * abstract function which creates the form to create / edit the answers of the question
  932. * @param the formvalidator instance
  933. */
  934. abstract function createAnswersForm ($form);
  935. /**
  936. * abstract function which process the creation of answers
  937. * @param the formvalidator instance
  938. */
  939. abstract function processAnswersCreation ($form);
  940. /**
  941. * Displays the menu of question types
  942. */
  943. static function display_type_menu ($feedbacktype = 0)
  944. {
  945. global $exerciseId;
  946. // 1. by default we show all the question types
  947. $question_type_custom_list = self::$questionTypes;
  948. if (!isset($feedbacktype)) $feedbacktype=0;
  949. if ($feedbacktype==1) {
  950. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  951. $question_type_custom_list = array ( UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER]);
  952. }
  953. echo '<ul class="question_menu" style="padding:0px; margin:-2px;">';
  954. foreach ($question_type_custom_list as $i=>$a_type) {
  955. // include the class of the type
  956. include_once($a_type[0]);
  957. // get the picture of the type and the langvar which describes it
  958. eval('$img = '.$a_type[1].'::$typePicture;');
  959. eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
  960. echo '<li>';
  961. echo '<div class="icon_image_content">';
  962. echo '<a href="admin.php?newQuestion=yes&answerType='.$i.'">'.Display::return_icon($img, $explanation).'</a>';
  963. echo '<br>';
  964. echo '<a href="admin.php?newQuestion=yes&answerType='.$i.'">'.$explanation.'</a>';
  965. echo '</div>';
  966. echo '</li>';
  967. }
  968. echo '<li>';
  969. echo '<div class="icon_image_content">';
  970. if ($feedbacktype==1) {
  971. echo $url = '<a href="question_pool.php?type=1&fromExercise='.$exerciseId.'">';
  972. } else {
  973. echo $url = '<a href="question_pool.php?fromExercise='.$exerciseId.'">';
  974. }
  975. echo Display::return_icon('database.gif', get_lang('GetExistingQuestion'), '');
  976. echo '</a><br>';
  977. echo $url;
  978. echo get_lang('GetExistingQuestion');
  979. echo '</a>';
  980. echo '</div></li>';
  981. echo '</ul>';
  982. }
  983. static function get_types_information()
  984. {
  985. return self::$questionTypes;
  986. }
  987. }
  988. endif;
  989. ?>