question.class.php 37 KB

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