question.class.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * File containing the Question class.
  5. * @package chamilo.exercise
  6. * @author Olivier Brouckaert
  7. * @author Julio Montoya <gugli100@gmail.com> lot of bug fixes
  8. * Modified by hubert.borderiou@grenet.fr - add question categories
  9. */
  10. /**
  11. * Code
  12. */
  13. if(!class_exists('Question')):
  14. // answer types
  15. define('UNIQUE_ANSWER', 1);
  16. define('MULTIPLE_ANSWER', 2);
  17. define('FILL_IN_BLANKS', 3);
  18. define('MATCHING', 4);
  19. define('FREE_ANSWER', 5);
  20. define('HOT_SPOT', 6);
  21. define('HOT_SPOT_ORDER', 7);
  22. define('HOT_SPOT_DELINEATION', 8);
  23. define('MULTIPLE_ANSWER_COMBINATION', 9);
  24. define('UNIQUE_ANSWER_NO_OPTION', 10);
  25. define('MULTIPLE_ANSWER_TRUE_FALSE', 11);
  26. define('MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE', 12);
  27. define('ORAL_EXPRESSION', 13);
  28. if (!class_exists('Category')) include_once("testcategory.class.php"); // hub 12-10-2011
  29. /**
  30. QUESTION CLASS
  31. *
  32. * This class allows to instantiate an object of type Question
  33. *
  34. * @author Olivier Brouckaert, original author
  35. * @author Patrick Cool, LaTeX support
  36. * @package chamilo.exercise
  37. */
  38. abstract class Question
  39. {
  40. public $id;
  41. public $question;
  42. public $description;
  43. public $weighting;
  44. public $position;
  45. public $type;
  46. public $level;
  47. public $picture;
  48. public $exerciseList; // array with the list of exercises which this question is in
  49. public $category; // hub 12-10-2011
  50. private $isContent;
  51. public $course;
  52. static $typePicture = 'new_question.png';
  53. static $explanationLangVar = '';
  54. static $questionTypes = array(
  55. UNIQUE_ANSWER => array('unique_answer.class.php' , 'UniqueAnswer'),
  56. MULTIPLE_ANSWER => array('multiple_answer.class.php' , 'MultipleAnswer'),
  57. FILL_IN_BLANKS => array('fill_blanks.class.php' , 'FillBlanks'),
  58. MATCHING => array('matching.class.php' , 'Matching'),
  59. FREE_ANSWER => array('freeanswer.class.php' , 'FreeAnswer'),
  60. ORAL_EXPRESSION => array('oral_expression.class.php' , 'OralExpression'),
  61. HOT_SPOT => array('hotspot.class.php' , 'HotSpot'),
  62. HOT_SPOT_DELINEATION => array('hotspot.class.php' , 'HotspotDelineation'),
  63. MULTIPLE_ANSWER_COMBINATION => array('multiple_answer_combination.class.php' , 'MultipleAnswerCombination'),
  64. UNIQUE_ANSWER_NO_OPTION => array('unique_answer_no_option.class.php' , 'UniqueAnswerNoOption'),
  65. MULTIPLE_ANSWER_TRUE_FALSE => array('multiple_answer_true_false.class.php' , 'MultipleAnswerTrueFalse'),
  66. MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE => array('multiple_answer_combination_true_false.class.php' , 'MultipleAnswerCombinationTrueFalse')
  67. );
  68. /**
  69. * constructor of the class
  70. *
  71. * @author - Olivier Brouckaert
  72. */
  73. public function Question() {
  74. $this->id=0;
  75. $this->question='';
  76. $this->description='';
  77. $this->weighting=0;
  78. $this->position=1;
  79. $this->picture='';
  80. $this->level = 1;
  81. $this->category=0; // hub 12-10-2011
  82. $this->extra='';
  83. $this->exerciseList=array();
  84. $this->course = api_get_course_info();
  85. }
  86. public function getIsContent() {
  87. $isContent = null;
  88. if (isset($_REQUEST['isContent'])) {
  89. $isContent = intval($_REQUEST['isContent']);
  90. }
  91. return $this->isContent = $isContent;
  92. }
  93. /**
  94. * Reads question informations from the data base
  95. *
  96. * @author - Olivier Brouckaert
  97. * @param - integer $id - question ID
  98. * @return - boolean - true if question exists, otherwise false
  99. */
  100. static function read($id, $course_id = null) {
  101. $id = intval($id);
  102. if (!empty($course_id)) {
  103. $course_info = api_get_course_info_by_id($course_id);
  104. } else {
  105. $course_info = api_get_course_info();
  106. }
  107. $course_id = $course_info['real_id'];
  108. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  109. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  110. $sql = "SELECT question,description,ponderation,position,type,picture,level,extra FROM $TBL_QUESTIONS WHERE c_id = $course_id AND id = $id ";
  111. $result = Database::query($sql);
  112. // if the question has been found
  113. if ($object = Database::fetch_object($result)) {
  114. $objQuestion = Question::getInstance($object->type);
  115. if (!empty($objQuestion)) {
  116. $objQuestion->id = $id;
  117. $objQuestion->question = $object->question;
  118. $objQuestion->description = $object->description;
  119. $objQuestion->weighting = $object->ponderation;
  120. $objQuestion->position = $object->position;
  121. $objQuestion->type = $object->type;
  122. $objQuestion->picture = $object->picture;
  123. $objQuestion->level = (int) $object->level;
  124. $objQuestion->extra = $object->extra;
  125. $objQuestion->course = $course_info;
  126. $objQuestion->category = Testcategory::getCategoryForQuestion($id); // hub 12-10-2011
  127. $sql = "SELECT exercice_id FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id = $id";
  128. $result_exercise_list = Database::query($sql);
  129. // fills the array with the exercises which this question is in
  130. if ($result_exercise_list) {
  131. while ($obj = Database::fetch_object($result_exercise_list)) {
  132. $objQuestion->exerciseList[] = $obj->exercice_id;
  133. }
  134. }
  135. return $objQuestion;
  136. }
  137. }
  138. // question not found
  139. return false;
  140. }
  141. /**
  142. * returns the question ID
  143. *
  144. * @author - Olivier Brouckaert
  145. * @return - integer - question ID
  146. */
  147. function selectId() {
  148. return $this->id;
  149. }
  150. /**
  151. * returns the question title
  152. *
  153. * @author - Olivier Brouckaert
  154. * @return - string - question title
  155. */
  156. function selectTitle() {
  157. $this->question=text_filter($this->question);
  158. return $this->question;
  159. }
  160. /**
  161. * returns the question description
  162. *
  163. * @author - Olivier Brouckaert
  164. * @return - string - question description
  165. */
  166. function selectDescription() {
  167. $this->description=text_filter($this->description);
  168. return $this->description;
  169. }
  170. /**
  171. * returns the question weighting
  172. *
  173. * @author - Olivier Brouckaert
  174. * @return - integer - question weighting
  175. */
  176. function selectWeighting()
  177. {
  178. return $this->weighting;
  179. }
  180. /**
  181. * returns the question position
  182. *
  183. * @author - Olivier Brouckaert
  184. * @return - integer - question position
  185. */
  186. function selectPosition() {
  187. return $this->position;
  188. }
  189. /**
  190. * returns the answer type
  191. *
  192. * @author - Olivier Brouckaert
  193. * @return - integer - answer type
  194. */
  195. function selectType() {
  196. return $this->type;
  197. }
  198. /**
  199. * returns the level of the question
  200. *
  201. * @author - Nicolas Raynaud
  202. * @return - integer - level of the question, 0 by default.
  203. */
  204. function selectLevel() {
  205. return $this->level;
  206. }
  207. /**
  208. * returns the picture name
  209. *
  210. * @author - Olivier Brouckaert
  211. * @return - string - picture name
  212. */
  213. function selectPicture() {
  214. return $this->picture;
  215. }
  216. function selectPicturePath() {
  217. if (!empty($this->picture)) {
  218. return api_get_path(WEB_COURSE_PATH).$this->course['path'].'/document/images/'.$this->picture;
  219. }
  220. return false;
  221. }
  222. /**
  223. * returns the array with the exercise ID list
  224. *
  225. * @author - Olivier Brouckaert
  226. * @return - array - list of exercise ID which the question is in
  227. */
  228. function selectExerciseList() {
  229. return $this->exerciseList;
  230. }
  231. /**
  232. * returns the number of exercises which this question is in
  233. *
  234. * @author - Olivier Brouckaert
  235. * @return - integer - number of exercises
  236. */
  237. function selectNbrExercises() {
  238. return sizeof($this->exerciseList);
  239. }
  240. /**
  241. * changes the question title
  242. *
  243. * @author - Olivier Brouckaert
  244. * @param - string $title - question title
  245. */
  246. function updateTitle($title) {
  247. $this->question=$title;
  248. }
  249. /**
  250. * changes the question description
  251. *
  252. * @author - Olivier Brouckaert
  253. * @param - string $description - question description
  254. */
  255. function updateDescription($description) {
  256. $this->description=$description;
  257. }
  258. /**
  259. * changes the question weighting
  260. *
  261. * @author - Olivier Brouckaert
  262. * @param - integer $weighting - question weighting
  263. */
  264. function updateWeighting($weighting) {
  265. $this->weighting=$weighting;
  266. }
  267. /**
  268. * @author - Hubert Borderiou 12-10-2011
  269. * @param - array of category $in_category
  270. */
  271. function updateCategory($in_category) {
  272. $this->category=$in_category;
  273. }
  274. /**
  275. * @author - Hubert Borderiou 12-10-2011
  276. * @param - interger $in_positive
  277. */
  278. function updateScoreAlwaysPositive($in_positive) {
  279. $this->scoreAlwaysPositive=$in_positive;
  280. }
  281. /**
  282. * @author - Hubert Borderiou 12-10-2011
  283. * @param - interger $in_positive
  284. */
  285. function updateUncheckedMayScore($in_positive) {
  286. $this->uncheckedMayScore=$in_positive;
  287. }
  288. /**
  289. * @author - Hubert Borderiou 12-10-2011
  290. * @param - interger $in_positive
  291. * in this version, a question can only have 1 category
  292. * if category is 0, then question has no category then delete the category entry
  293. */
  294. function saveCategory($in_category) {
  295. if ($in_category <= 0) {
  296. $this->deleteCategory();
  297. } else {
  298. // update or add category for a question
  299. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  300. $category_id = Database::escape_string($in_category);
  301. $question_id = Database::escape_string($this->id);
  302. $sql = "SELECT count(*) AS nb FROM $TBL_QUESTION_REL_CATEGORY WHERE question_id=$question_id AND c_id=".api_get_course_int_id();
  303. $res = Database::query($sql);
  304. $row = Database::fetch_array($res);
  305. if ($row['nb'] > 0){
  306. $sql = "UPDATE $TBL_QUESTION_REL_CATEGORY SET category_id=$category_id WHERE question_id=$question_id AND c_id=".api_get_course_int_id();
  307. $res = Database::query($sql);
  308. } else {
  309. $sql = "INSERT INTO $TBL_QUESTION_REL_CATEGORY VALUES (".api_get_course_int_id().", $question_id, $category_id)";
  310. $res = Database::query($sql);
  311. }
  312. }
  313. }
  314. /**
  315. * @author hubert borderiou 12-10-2011
  316. * delete any category entry for question id
  317. * @param : none
  318. * delte the category for question
  319. */
  320. function deleteCategory() {
  321. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  322. $question_id = Database::escape_string($this->id);
  323. $sql = "DELETE FROM $TBL_QUESTION_REL_CATEGORY WHERE question_id=$question_id AND c_id=".api_get_course_int_id();
  324. $res = Database::query($sql);
  325. }
  326. /**
  327. * changes the question position
  328. *
  329. * @author - Olivier Brouckaert
  330. * @param - integer $position - question position
  331. */
  332. function updatePosition($position) {
  333. $this->position=$position;
  334. }
  335. /**
  336. * changes the question level
  337. *
  338. * @author - Nicolas Raynaud
  339. * @param - integer $level - question level
  340. */
  341. function updateLevel($level) {
  342. $this->level=$level;
  343. }
  344. /**
  345. * changes the answer type. If the user changes the type from "unique answer" to "multiple answers"
  346. * (or conversely) answers are not deleted, otherwise yes
  347. *
  348. * @author - Olivier Brouckaert
  349. * @param - integer $type - answer type
  350. */
  351. function updateType($type) {
  352. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  353. $course_id = $this->course['real_id'];
  354. if (empty($course_id)) {
  355. $course_id = api_get_course_int_id();
  356. }
  357. // if we really change the type
  358. if($type != $this->type) {
  359. // if we don't change from "unique answer" to "multiple answers" (or conversely)
  360. if(!in_array($this->type,array(UNIQUE_ANSWER,MULTIPLE_ANSWER)) || !in_array($type,array(UNIQUE_ANSWER,MULTIPLE_ANSWER))) {
  361. // removes old answers
  362. $sql="DELETE FROM $TBL_REPONSES WHERE c_id = $course_id AND question_id='".Database::escape_string($this->id)."'";
  363. Database::query($sql);
  364. }
  365. $this->type=$type;
  366. }
  367. }
  368. /**
  369. * adds a picture to the question
  370. *
  371. * @author - Olivier Brouckaert
  372. * @param - string $Picture - temporary path of the picture to upload
  373. * @param - string $PictureName - Name of the picture
  374. * @return - boolean - true if uploaded, otherwise false
  375. */
  376. function uploadPicture($Picture,$PictureName) {
  377. global $picturePath;
  378. if (!file_exists($picturePath)) {
  379. if (mkdir($picturePath, api_get_permissions_for_new_directories())) {
  380. // document path
  381. $documentPath = api_get_path(SYS_COURSE_PATH) . $this->course['path'] . "/document";
  382. $path = str_replace($documentPath,'',$picturePath);
  383. $title_path = basename($picturePath);
  384. $doc_id = add_document($this->course, $path, 'folder', 0,$title_path);
  385. api_item_property_update($this->course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
  386. }
  387. }
  388. // if the question has got an ID
  389. if ($this->id) {
  390. $extension = pathinfo($PictureName, PATHINFO_EXTENSION);
  391. $this->picture = 'quiz-'.$this->id.'.jpg';
  392. $o_img = new Image($Picture);
  393. $o_img->send_image($picturePath.'/'.$this->picture, -1, 'jpg');
  394. $document_id = add_document($this->course, '/images/'.$this->picture, 'file', filesize($picturePath.'/'.$this->picture),$this->picture);
  395. if ($document_id) {
  396. return api_item_property_update($this->course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id);
  397. }
  398. }
  399. return false;
  400. }
  401. /**
  402. * Resizes a picture || Warning!: can only be called after uploadPicture, or if picture is already available in object.
  403. *
  404. * @author - Toon Keppens
  405. * @param - string $Dimension - Resizing happens proportional according to given dimension: height|width|any
  406. * @param - integer $Max - Maximum size
  407. * @return - boolean - true if success, false if failed
  408. */
  409. function resizePicture($Dimension, $Max) {
  410. global $picturePath;
  411. // if the question has an ID
  412. if($this->id) {
  413. // Get dimensions from current image.
  414. $my_image = new Image($picturePath.'/'.$this->picture);
  415. $current_image_size = $my_image->get_image_size();
  416. $current_width = $current_image_size['width'];
  417. $current_height = $current_image_size['height'];
  418. if($current_width < $Max && $current_height <$Max)
  419. return true;
  420. elseif($current_height == "")
  421. return false;
  422. // Resize according to height.
  423. if ($Dimension == "height") {
  424. $resize_scale = $current_height / $Max;
  425. $new_height = $Max;
  426. $new_width = ceil($current_width / $resize_scale);
  427. }
  428. // Resize according to width
  429. if ($Dimension == "width") {
  430. $resize_scale = $current_width / $Max;
  431. $new_width = $Max;
  432. $new_height = ceil($current_height / $resize_scale);
  433. }
  434. // Resize according to height or width, both should not be larger than $Max after resizing.
  435. if ($Dimension == "any") {
  436. if ($current_height > $current_width || $current_height == $current_width)
  437. {
  438. $resize_scale = $current_height / $Max;
  439. $new_height = $Max;
  440. $new_width = ceil($current_width / $resize_scale);
  441. }
  442. if ($current_height < $current_width)
  443. {
  444. $resize_scale = $current_width / $Max;
  445. $new_width = $Max;
  446. $new_height = ceil($current_height / $resize_scale);
  447. }
  448. }
  449. $my_image->resize($new_width, $new_height);
  450. $result = $my_image->send_image($picturePath.'/'.$this->picture);
  451. if ($result) {
  452. return true;
  453. } else {
  454. return false;
  455. }
  456. }
  457. }
  458. /**
  459. * deletes the picture
  460. *
  461. * @author - Olivier Brouckaert
  462. * @return - boolean - true if removed, otherwise false
  463. */
  464. function removePicture() {
  465. global $picturePath;
  466. // if the question has got an ID and if the picture exists
  467. if($this->id) {
  468. $picture=$this->picture;
  469. $this->picture='';
  470. return @unlink($picturePath.'/'.$picture)?true:false;
  471. }
  472. return false;
  473. }
  474. /**
  475. * Exports a picture to another question
  476. *
  477. * @author - Olivier Brouckaert
  478. * @param - integer $questionId - ID of the target question
  479. * @return - boolean - true if copied, otherwise false
  480. */
  481. function exportPicture($questionId, $course_info) {
  482. $course_id = $course_info['real_id'];
  483. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION, $course_info['db_name']);
  484. $destination_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/images';
  485. $source_path = api_get_path(SYS_COURSE_PATH).$this->course['path'].'/document/images';
  486. // if the question has got an ID and if the picture exists
  487. if($this->id && !empty($this->picture)) {
  488. $picture=explode('.',$this->picture);
  489. $Extension=$picture[sizeof($picture)-1];
  490. $picture='quiz-'.$questionId.'.'.$Extension;
  491. $sql="UPDATE $TBL_QUESTIONS SET picture='".Database::escape_string($picture)."' WHERE c_id = $course_id AND id='".intval($questionId)."'";
  492. Database::query($sql);
  493. return @copy($source_path.'/'.$this->picture, $destination_path.'/'.$picture)?true:false;
  494. }
  495. return false;
  496. }
  497. /**
  498. * Saves the picture coming from POST into a temporary file
  499. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  500. * For example, if we first show a confirmation box.
  501. *
  502. * @author - Olivier Brouckaert
  503. * @param - string $Picture - temporary path of the picture to move
  504. * @param - string $PictureName - Name of the picture
  505. */
  506. function setTmpPicture($Picture,$PictureName) {
  507. global $picturePath;
  508. $PictureName=explode('.',$PictureName);
  509. $Extension=$PictureName[sizeof($PictureName)-1];
  510. // saves the picture into a temporary file
  511. @move_uploaded_file($Picture,$picturePath.'/tmp.'.$Extension);
  512. }
  513. /**
  514. Sets the title
  515. */
  516. public function setTitle($title) {
  517. $this->question = $title;
  518. }
  519. /**
  520. Sets the title
  521. */
  522. public function setExtra($extra) {
  523. $this->extra = $extra;
  524. }
  525. /**
  526. * Moves the temporary question "tmp" to "quiz-$questionId"
  527. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  528. * For example, if we first show a confirmation box.
  529. *
  530. * @author - Olivier Brouckaert
  531. * @return - boolean - true if moved, otherwise false
  532. */
  533. function getTmpPicture() {
  534. global $picturePath;
  535. // if the question has got an ID and if the picture exists
  536. if($this->id) {
  537. if(file_exists($picturePath.'/tmp.jpg')) {
  538. $Extension='jpg';
  539. }
  540. elseif(file_exists($picturePath.'/tmp.gif'))
  541. {
  542. $Extension='gif';
  543. }
  544. elseif(file_exists($picturePath.'/tmp.png'))
  545. {
  546. $Extension='png';
  547. }
  548. $this->picture='quiz-'.$this->id.'.'.$Extension;
  549. return @rename($picturePath.'/tmp.'.$Extension,$picturePath.'/'.$this->picture)?true:false;
  550. }
  551. return false;
  552. }
  553. /**
  554. * updates the question in the data base
  555. * if an exercise ID is provided, we add that exercise ID into the exercise list
  556. *
  557. * @author - Olivier Brouckaert
  558. * @param - integer $exerciseId - exercise ID if saving in an exercise
  559. */
  560. function save($exerciseId=0) {
  561. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  562. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  563. $id = $this->id;
  564. $question = $this->question;
  565. $description = $this->description;
  566. $weighting = $this->weighting;
  567. $position = $this->position;
  568. $type = $this->type;
  569. $picture = $this->picture;
  570. $level = $this->level;
  571. $extra = $this->extra;
  572. $c_id = $this->course['real_id'];
  573. $category = $this->category;
  574. // question already exists
  575. if(!empty($id)) {
  576. $sql="UPDATE $TBL_QUESTIONS SET
  577. question ='".Database::escape_string($question)."',
  578. description ='".Database::escape_string($description)."',
  579. ponderation ='".Database::escape_string($weighting)."',
  580. position ='".Database::escape_string($position)."',
  581. type ='".Database::escape_string($type)."',
  582. picture ='".Database::escape_string($picture)."',
  583. extra ='".Database::escape_string($extra)."',
  584. level ='".Database::escape_string($level)."'
  585. WHERE c_id = $c_id AND id='".Database::escape_string($id)."'";
  586. Database::query($sql);
  587. $this->saveCategory($category); // hub 12-10-2011
  588. if (!empty($exerciseId)) {
  589. api_item_property_update($this->course, TOOL_QUIZ, $id,'QuizQuestionUpdated',api_get_user_id);
  590. }
  591. if (api_get_setting('search_enabled')=='true') {
  592. if ($exerciseId != 0) {
  593. $this -> search_engine_edit($exerciseId);
  594. } else {
  595. /**
  596. * actually there is *not* an user interface for
  597. * creating questions without a relation with an exercise
  598. */
  599. }
  600. }
  601. } else {
  602. // creates a new question
  603. $sql = "SELECT max(position) FROM $TBL_QUESTIONS as question, $TBL_EXERCICE_QUESTION as test_question
  604. WHERE question.id = test_question.question_id AND
  605. test_question.exercice_id = '".Database::escape_string($exerciseId)."' AND
  606. question.c_id = $c_id AND
  607. test_question.c_id = $c_id ";
  608. $result = Database::query($sql);
  609. $current_position = Database::result($result,0,0);
  610. $this->updatePosition($current_position+1);
  611. $position = $this->position;
  612. $sql = "INSERT INTO $TBL_QUESTIONS (c_id, question, description, ponderation, position, type, picture, extra, level) VALUES (
  613. $c_id,
  614. '".Database::escape_string($question)."',
  615. '".Database::escape_string($description)."',
  616. '".Database::escape_string($weighting)."',
  617. '".Database::escape_string($position)."',
  618. '".Database::escape_string($type)."',
  619. '".Database::escape_string($picture)."',
  620. '".Database::escape_string($extra)."',
  621. '".Database::escape_string($level)."'
  622. )";
  623. Database::query($sql);
  624. $this->id = Database::insert_id();
  625. api_item_property_update($this->course, TOOL_QUIZ, $this->id,'QuizQuestionAdded',api_get_user_id());
  626. // If hotspot, create first answer
  627. if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) {
  628. $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
  629. $sql = "INSERT INTO $TBL_ANSWERS (c_id, id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type )
  630. VALUES (".$c_id.", '1', '".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'square')";
  631. Database::query($sql);
  632. }
  633. if ($type == HOT_SPOT_DELINEATION ) {
  634. $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
  635. $sql="INSERT INTO $TBL_ANSWERS (c_id, id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type )
  636. VALUES (".$c_id.", '1', '".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'delineation')";
  637. Database::query($sql);
  638. }
  639. if (api_get_setting('search_enabled')=='true') {
  640. if ($exerciseId != 0) {
  641. $this -> search_engine_edit($exerciseId, TRUE);
  642. } else {
  643. /**
  644. * actually there is *not* an user interface for
  645. * creating questions without a relation with an exercise
  646. */
  647. }
  648. }
  649. }
  650. // if the question is created in an exercise
  651. if($exerciseId) {
  652. /*
  653. $sql = 'UPDATE '.Database::get_course_table(TABLE_LP_ITEM).'
  654. SET max_score = '.intval($weighting).'
  655. WHERE item_type = "'.TOOL_QUIZ.'"
  656. AND path='.intval($exerciseId);
  657. Database::query($sql);
  658. */
  659. // adds the exercise into the exercise list of this question
  660. $this->addToList($exerciseId, TRUE);
  661. }
  662. }
  663. function search_engine_edit($exerciseId, $addQs=FALSE, $rmQs=FALSE) {
  664. // update search engine and its values table if enabled
  665. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  666. $course_id = api_get_course_id();
  667. // get search_did
  668. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  669. if ($addQs || $rmQs) {
  670. //there's only one row per question on normal db and one document per question on search engine db
  671. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
  672. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  673. } else {
  674. $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';
  675. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  676. }
  677. $res = Database::query($sql);
  678. if (Database::num_rows($res) > 0 || $addQs) {
  679. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  680. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  681. $di = new DokeosIndexer();
  682. if ($addQs) {
  683. $question_exercises = array((int)$exerciseId);
  684. } else {
  685. $question_exercises = array();
  686. }
  687. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  688. $di->connectDb(NULL, NULL, $lang);
  689. // retrieve others exercise ids
  690. $se_ref = Database::fetch_array($res);
  691. $se_doc = $di->get_document((int)$se_ref['search_did']);
  692. if ($se_doc !== FALSE) {
  693. if ( ($se_doc_data=$di->get_document_data($se_doc)) !== FALSE ) {
  694. $se_doc_data = unserialize($se_doc_data);
  695. if (isset($se_doc_data[SE_DATA]['type']) && $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION) {
  696. if (isset($se_doc_data[SE_DATA]['exercise_ids']) && is_array($se_doc_data[SE_DATA]['exercise_ids'])) {
  697. foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
  698. if (!in_array($old_value, $question_exercises)) {
  699. $question_exercises[] = $old_value;
  700. }
  701. }
  702. }
  703. }
  704. }
  705. }
  706. if ($rmQs) {
  707. while ( ($key=array_search($exerciseId, $question_exercises)) !== FALSE) {
  708. unset($question_exercises[$key]);
  709. }
  710. }
  711. // build the chunk to index
  712. $ic_slide = new IndexableChunk();
  713. $ic_slide->addValue("title", $this->question);
  714. $ic_slide->addCourseId($course_id);
  715. $ic_slide->addToolId(TOOL_QUIZ);
  716. $xapian_data = array(
  717. SE_COURSE_ID => $course_id,
  718. SE_TOOL_ID => TOOL_QUIZ,
  719. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_QUESTION, 'exercise_ids' => $question_exercises, 'question_id' => (int)$this->id),
  720. SE_USER => (int)api_get_user_id(),
  721. );
  722. $ic_slide->xapian_data = serialize($xapian_data);
  723. $ic_slide->addValue("content", $this->description);
  724. //TODO: index answers, see also form validation on question_admin.inc.php
  725. $di->remove_document((int)$se_ref['search_did']);
  726. $di->addChunk($ic_slide);
  727. //index and return search engine document id
  728. if (!empty($question_exercises)) { // if empty there is nothing to index
  729. $did = $di->index();
  730. unset($di);
  731. }
  732. if ($did || $rmQs) {
  733. // save it to db
  734. if ($addQs || $rmQs) {
  735. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=\'%s\'';
  736. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  737. } else {
  738. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\' AND ref_id_second_level=\'%s\'';
  739. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  740. }
  741. Database::query($sql);
  742. if ($rmQs) {
  743. if (!empty($question_exercises)) {
  744. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  745. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  746. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, array_shift($question_exercises), $this->id, $did);
  747. Database::query($sql);
  748. }
  749. } else {
  750. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  751. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  752. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
  753. Database::query($sql);
  754. }
  755. }
  756. }
  757. }
  758. }
  759. /**
  760. * adds an exercise into the exercise list
  761. *
  762. * @author - Olivier Brouckaert
  763. * @param - integer $exerciseId - exercise ID
  764. * @param - boolean $fromSave - comming from $this->save() or not
  765. */
  766. function addToList($exerciseId, $fromSave = FALSE) {
  767. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION, $this->course['db_name']);
  768. $id = $this->id;
  769. // checks if the exercise ID is not in the list
  770. if (!in_array($exerciseId,$this->exerciseList)) {
  771. $this->exerciseList[]=$exerciseId;
  772. $new_exercise = new Exercise();
  773. $new_exercise->read($exerciseId);
  774. $count = $new_exercise->selectNbrQuestions();
  775. $count++;
  776. $sql="INSERT INTO $TBL_EXERCICE_QUESTION (c_id, question_id, exercice_id, question_order) VALUES
  777. ({$this->course['real_id']}, '".Database::escape_string($id)."','".Database::escape_string($exerciseId)."', '$count' )";
  778. Database::query($sql);
  779. // we do not want to reindex if we had just saved adnd indexed the question
  780. if (!$fromSave) {
  781. $this->search_engine_edit($exerciseId, TRUE);
  782. }
  783. }
  784. }
  785. /**
  786. * removes an exercise from the exercise list
  787. *
  788. * @author - Olivier Brouckaert
  789. * @param - integer $exerciseId - exercise ID
  790. * @return - boolean - true if removed, otherwise false
  791. */
  792. function removeFromList($exerciseId) {
  793. global $TBL_EXERCICE_QUESTION;
  794. $id = $this->id;
  795. // searches the position of the exercise ID in the list
  796. $pos=array_search($exerciseId,$this->exerciseList);
  797. $course_id = api_get_course_int_id();
  798. // exercise not found
  799. if($pos === false) {
  800. return false;
  801. } else {
  802. // deletes the position in the array containing the wanted exercise ID
  803. unset($this->exerciseList[$pos]);
  804. //update order of other elements
  805. $sql = "SELECT question_order FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."' AND exercice_id='".Database::escape_string($exerciseId)."'";
  806. $res = Database::query($sql);
  807. if (Database::num_rows($res)>0) {
  808. $row = Database::fetch_array($res);
  809. if (!empty($row['question_order'])) {
  810. $sql = "UPDATE $TBL_EXERCICE_QUESTION SET question_order = question_order-1
  811. WHERE c_id = $course_id AND exercice_id='".Database::escape_string($exerciseId)."' AND question_order > ".$row['question_order'];
  812. $res = Database::query($sql);
  813. }
  814. }
  815. $sql="DELETE FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."' AND exercice_id='".Database::escape_string($exerciseId)."'";
  816. Database::query($sql);
  817. return true;
  818. }
  819. }
  820. /**
  821. * Deletes a question from the database
  822. * the parameter tells if the question is removed from all exercises (value = 0),
  823. * or just from one exercise (value = exercise ID)
  824. *
  825. * @author - Olivier Brouckaert
  826. * @param - integer $deleteFromEx - exercise ID if the question is only removed from one exercise
  827. */
  828. function delete($deleteFromEx=0) {
  829. $course_id = api_get_course_int_id();
  830. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  831. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  832. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  833. $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  834. $id=$this->id;
  835. // if the question must be removed from all exercises
  836. if(!$deleteFromEx) {
  837. //update the question_order of each question to avoid inconsistencies
  838. $sql = "SELECT exercice_id, question_order FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."'";
  839. $res = Database::query($sql);
  840. if (Database::num_rows($res)>0) {
  841. while ($row = Database::fetch_array($res)) {
  842. if (!empty($row['question_order'])) {
  843. $sql = "UPDATE $TBL_EXERCICE_QUESTION SET question_order = question_order-1 WHERE c_id = $course_id AND exercice_id='".Database::escape_string($row['exercice_id'])."' AND question_order > ".$row['question_order'];
  844. $res = Database::query($sql);
  845. }
  846. }
  847. }
  848. $sql="DELETE FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."'";
  849. Database::query($sql);
  850. $sql="DELETE FROM $TBL_QUESTIONS WHERE c_id = $course_id AND id='".Database::escape_string($id)."'";
  851. Database::query($sql);
  852. $sql="DELETE FROM $TBL_REPONSES WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."'";
  853. Database::query($sql);
  854. // hub 12-10-2011 remove the category of this question in the question_rel_category table
  855. $sql = "DELETE FROM $TBL_QUIZ_QUESTION_REL_CATEGORY WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."' AND c_id=".api_get_course_int_id();
  856. Database::query($sql);
  857. api_item_property_update($this->course, TOOL_QUIZ, $id,'QuizQuestionDeleted',api_get_user_id());
  858. $this->removePicture();
  859. // resets the object
  860. $this->Question();
  861. } else {
  862. // just removes the exercise from the list
  863. $this->removeFromList($deleteFromEx);
  864. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  865. // disassociate question with this exercise
  866. $this -> search_engine_edit($deleteFromEx, FALSE, TRUE);
  867. }
  868. api_item_property_update($this->course, TOOL_QUIZ, $id,'QuizQuestionDeleted',api_get_user_id());
  869. }
  870. }
  871. /**
  872. * Duplicates the question
  873. *
  874. * @author Olivier Brouckaert
  875. * @param array Course info of the destination course
  876. * @return int ID of the new question
  877. */
  878. function duplicate($course_info = null) {
  879. if (empty($course_info)) {
  880. $course_info = $this->course;
  881. } else {
  882. $course_info = $course_info;
  883. }
  884. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  885. $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  886. $question = $this->question;
  887. $description = $this->description;
  888. $weighting = $this->weighting;
  889. $position = $this->position;
  890. $type = $this->type;
  891. $level = intval($this->level);
  892. $extra = $this->extra;
  893. //Using the same method used in the course copy to transform URLs
  894. require_once api_get_path(LIBRARY_PATH).'document.lib.php';
  895. if ($course_info['db_name'] != $this->course['db_name']) {
  896. $description = DocumentManager::replace_urls_inside_content_html_from_copy_course($description, $this->course['id'], $course_info['id']);
  897. $question = DocumentManager::replace_urls_inside_content_html_from_copy_course($question, $this->course['id'], $course_info['id']);
  898. }
  899. $course_id = $course_info['real_id'];
  900. $options = self::readQuestionOption($this->id, $course_id);
  901. //Inserting in the new course db / or the same course db
  902. $sql = "INSERT INTO $TBL_QUESTIONS (c_id, question, description, ponderation, position, type, level, extra )
  903. VALUES('$course_id', '".Database::escape_string($question)."','".Database::escape_string($description)."','".Database::escape_string($weighting)."','".Database::escape_string($position)."','".Database::escape_string($type)."' ,'".Database::escape_string($level)."' ,'".Database::escape_string($extra)."' )";
  904. Database::query($sql);
  905. $new_question_id = Database::insert_id();
  906. if (!empty($options)) {
  907. //Saving the quiz_options
  908. foreach ($options as $item) {
  909. $item['question_id'] = $new_question_id;
  910. $item['c_id'] = $course_id;
  911. unset($item['id']);
  912. Database::insert($TBL_QUESTION_OPTIONS, $item);
  913. }
  914. }
  915. // Duplicates the picture
  916. $this->exportPicture($new_question_id, $course_info);
  917. return $new_question_id;
  918. }
  919. function get_question_type($type) {
  920. if ($type == ORAL_EXPRESSION && api_get_setting('enable_nanogong') != 'true') {
  921. return null;
  922. }
  923. return self::$questionTypes[$type];
  924. }
  925. function get_question_type_list() {
  926. if (api_get_setting('enable_nanogong') != 'true') {
  927. self::$questionTypes[ORAL_EXPRESSION] = null;
  928. unset(self::$questionTypes[ORAL_EXPRESSION]);
  929. }
  930. return self::$questionTypes;
  931. }
  932. /**
  933. * Returns an instance of the class corresponding to the type
  934. * @param integer $type the type of the question
  935. * @return an instance of a Question subclass (or of Questionc class by default)
  936. */
  937. static function getInstance($type) {
  938. if (!is_null($type)) {
  939. list($file_name, $class_name) = self::get_question_type($type);
  940. if (!empty($file_name)) {
  941. include_once $file_name;
  942. if (class_exists($class_name)) {
  943. return new $class_name();
  944. } else {
  945. echo 'Can\'t instanciate class '.$class_name.' of type '.$type;
  946. }
  947. }
  948. }
  949. return null;
  950. }
  951. /**
  952. * Creates the form to create / edit a question
  953. * A subclass can redifine this function to add fields...
  954. * @param FormValidator $form the formvalidator instance (by reference)
  955. */
  956. function createForm (&$form,$fck_config=0) {
  957. echo ' <style>
  958. .media { display:none;}
  959. </style>';
  960. echo '<script>
  961. // hack to hide http://cksource.com/forums/viewtopic.php?f=6&t=8700
  962. function FCKeditor_OnComplete( editorInstance )
  963. {
  964. if (document.getElementById ( \'HiddenFCK\' + editorInstance.Name )) {
  965. HideFCKEditorByInstanceName (editorInstance.Name);
  966. }
  967. }
  968. function HideFCKEditorByInstanceName ( editorInstanceName ) {
  969. if (document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className == "HideFCKEditor" ) {
  970. document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className = "media";
  971. }
  972. }
  973. function show_media()
  974. {
  975. var my_display = document.getElementById(\'HiddenFCKquestionDescription\').style.display;
  976. if(my_display== \'none\' || my_display == \'\') {
  977. document.getElementById(\'HiddenFCKquestionDescription\').style.display = \'block\';
  978. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;<img style="vertical-align: middle;" src="../img/looknfeelna.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'\';
  979. } else {
  980. document.getElementById(\'HiddenFCKquestionDescription\').style.display = \'none\';
  981. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;<img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'\';
  982. }
  983. }
  984. // hub 13-12-2010
  985. function visiblerDevisibler(in_id) {
  986. if (document.getElementById(in_id)) {
  987. if (document.getElementById(in_id).style.display == "none") {
  988. document.getElementById(in_id).style.display = "block";
  989. if (document.getElementById(in_id+"Img")) {
  990. document.getElementById(in_id+"Img").src = "../img/div_hide.gif";
  991. }
  992. }
  993. else {
  994. document.getElementById(in_id).style.display = "none";
  995. if (document.getElementById(in_id+"Img")) {
  996. document.getElementById(in_id+"Img").src = "../img/div_show.gif";
  997. }
  998. }
  999. }
  1000. }
  1001. </script>';
  1002. $renderer = $form->defaultRenderer();
  1003. $form->addElement('html','<div class="form">');
  1004. // question name
  1005. $form->addElement('text','questionName','<span class="form_required">*</span> '.get_lang('Question'),'size="80"');
  1006. //$form->applyFilter('questionName','html_filter');
  1007. //$radios_results_enabled[] = $form->createElement('static', null, null, null);
  1008. //$test=FormValidator :: createElement ('text', 'questionName');
  1009. //$radios_results_enabled[]=$test;
  1010. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw" >{element}</div></div>','questionName');
  1011. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>','questionLevel');
  1012. //
  1013. // Enrich question
  1014. //
  1015. $form->addRule('questionName', get_lang('GiveQuestion'), 'required');
  1016. // default content
  1017. $isContent = isset($_REQUEST['isContent']) ? intval($_REQUEST['isContent']) : null;
  1018. // question type
  1019. $answerType= intval($_REQUEST['answerType']);
  1020. $form->addElement('hidden','answerType',$_REQUEST['answerType']);
  1021. // html editor
  1022. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  1023. if(is_array($fck_config)){
  1024. $editor_config = array_merge($editor_config, $fck_config);
  1025. }
  1026. if(!api_is_allowed_to_edit(null,true)) $editor_config['UserStatus'] = 'student';
  1027. $form -> addElement('html','<div class="row">
  1028. <div class="label"></div>
  1029. <div class="formw" style="height:50px">
  1030. <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>
  1031. </div>
  1032. </div>');
  1033. $form -> addElement ('html','<div class="HideFCKEditor" id="HiddenFCKquestionDescription" >');
  1034. $form->add_html_editor('questionDescription', get_lang('langQuestionDescription'), false, false, $editor_config);
  1035. $form -> addElement ('html','</div>');
  1036. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>','questionDescription');
  1037. //
  1038. // Advanced parameters
  1039. //
  1040. // question level
  1041. //@todo move levles into a table
  1042. $select_level = array (1,2,3,4,5);
  1043. //$radios_results_enabled[] =
  1044. foreach($select_level as $val) {
  1045. $radios_results_enabled[] = FormValidator :: createElement ('radio', null, null,$val,$val);
  1046. }
  1047. $form->addGroup($radios_results_enabled,'questionLevel',get_lang('Difficulty'));
  1048. // HUB 12-10-2011
  1049. // categories
  1050. $tabCat = array();
  1051. $tabCat = Testcategory::getCategoriesIdAndName();
  1052. $form->addElement('select', 'questionCategory', get_lang('Category'), $tabCat);
  1053. // note always positive for multiple answer questions
  1054. // Form's style
  1055. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>&nbsp;','questionName');
  1056. $renderer->setElementTemplate('<div style="margin-left:0%;float:right;text-align:left;width:89%" class=""><a href="javascript:void(0)" onclick="visiblerDevisibler(\'id_advancedOption\')"><img id="id_advancedOptionImg" style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang("AdvancedParameters").'</a><div id="id_advancedOption" style="background-color:#EFEFEF;display:none;"><div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>','questionLevel');
  1057. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div><br/></div></div><div style="clear:both">&nbsp;</div>','questionCategory');
  1058. // fhub
  1059. // hidden values
  1060. $form->addElement('hidden','myid',$_REQUEST['myid']);
  1061. if (!isset($_GET['fromExercise'])) {
  1062. switch($answerType) {
  1063. case 1: $this->question = get_lang('langDefaultUniqueQuestion'); break;
  1064. case 2: $this->question = get_lang('langDefaultMultipleQuestion'); break;
  1065. case 3: $this->question = get_lang('langDefaultFillBlankQuestion'); break;
  1066. case 4: $this->question = get_lang('langDefaultMathingQuestion'); break;
  1067. case 5: $this->question = get_lang('langDefaultOpenQuestion'); break;
  1068. case 9: $this->question = get_lang('langDefaultMultipleQuestion'); break;
  1069. }
  1070. }
  1071. $form->addElement('html','</div>');
  1072. // default values
  1073. $defaults = array();
  1074. $defaults['questionName'] = $this -> question;
  1075. $defaults['questionDescription'] = $this -> description;
  1076. $defaults['questionLevel'] = $this -> level;
  1077. $defaults['questionCategory'] = $this->category; // hub 12-10-2011
  1078. //Came from he question pool
  1079. if (isset($_GET['fromExercise'])) {
  1080. $form->setDefaults($defaults);
  1081. }
  1082. if (!empty($_REQUEST['myid'])) {
  1083. $form->setDefaults($defaults);
  1084. } else {
  1085. if ($isContent == 1) {
  1086. $form->setDefaults($defaults);
  1087. }
  1088. }
  1089. }
  1090. /**
  1091. * function which process the creation of questions
  1092. * @param FormValidator $form the formvalidator instance
  1093. * @param Exercise $objExercise the Exercise instance
  1094. */
  1095. function processCreation ($form, $objExercise) {
  1096. $this -> updateTitle($form->getSubmitValue('questionName'));
  1097. $this -> updateDescription($form->getSubmitValue('questionDescription'));
  1098. $this -> updateLevel($form->getSubmitValue('questionLevel'));
  1099. $this->updateCategory($form->getSubmitValue('questionCategory')); // hub 12-10-2011
  1100. $this -> save($objExercise -> id);
  1101. // modify the exercise
  1102. $objExercise->addToList($this -> id);
  1103. $objExercise->update_question_positions();
  1104. }
  1105. /**
  1106. * abstract function which creates the form to create / edit the answers of the question
  1107. * @param the formvalidator instance
  1108. */
  1109. abstract function createAnswersForm ($form);
  1110. /**
  1111. * abstract function which process the creation of answers
  1112. * @param the formvalidator instance
  1113. */
  1114. abstract function processAnswersCreation ($form);
  1115. /**
  1116. * Displays the menu of question types
  1117. */
  1118. static function display_type_menu ($feedbacktype = 0) {
  1119. global $exerciseId;
  1120. $course_id = api_get_course_int_id();
  1121. // 1. by default we show all the question types
  1122. $question_type_custom_list = self::get_question_type_list();
  1123. if (!isset($feedbacktype)) $feedbacktype=0;
  1124. if ($feedbacktype==1) {
  1125. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  1126. //$question_type_custom_list = array ( UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER]);
  1127. $question_type_custom_list = array ( UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION]);
  1128. } else {
  1129. unset($question_type_custom_list[HOT_SPOT_DELINEATION]);
  1130. }
  1131. //blocking edition
  1132. $show_quiz_edition = true;
  1133. if (isset($exerciseId) && !empty($exerciseId)) {
  1134. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  1135. $sql="SELECT max_score FROM $TBL_LP_ITEM
  1136. WHERE c_id = $course_id AND item_type = '".TOOL_QUIZ."' AND path ='".Database::escape_string($exerciseId)."'";
  1137. $result = Database::query($sql);
  1138. if (Database::num_rows($result) > 0) {
  1139. $show_quiz_edition = false;
  1140. }
  1141. }
  1142. echo '<ul class="question_menu">';
  1143. foreach ($question_type_custom_list as $i=>$a_type) {
  1144. // include the class of the type
  1145. require_once($a_type[0]);
  1146. // get the picture of the type and the langvar which describes it
  1147. $img = $explanation = '';
  1148. eval('$img = '.$a_type[1].'::$typePicture;');
  1149. eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
  1150. echo '<li>';
  1151. echo '<div class="icon_image_content">';
  1152. if ($show_quiz_edition) {
  1153. echo '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.Display::return_icon($img, $explanation).'</a>';
  1154. //echo '<br>';
  1155. //echo '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.$explanation.'</a>';
  1156. } else {
  1157. $img = pathinfo($img);
  1158. $img = $img['filename'];
  1159. echo ''.Display::return_icon($img.'_na.gif',$explanation).'';
  1160. //echo '<br>';
  1161. //echo ''.$explanation.'';
  1162. }
  1163. echo '</div>';
  1164. echo '</li>';
  1165. }
  1166. echo '<li>';
  1167. echo '<div class="icon_image_content">';
  1168. if ($show_quiz_edition) {
  1169. if ($feedbacktype==1) {
  1170. echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&type=1&fromExercise='.$exerciseId.'">';
  1171. } else {
  1172. echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&fromExercise='.$exerciseId.'">';
  1173. }
  1174. echo Display::return_icon('database.png', get_lang('GetExistingQuestion'), '');
  1175. } else {
  1176. echo Display::return_icon('database_na.png', get_lang('GetExistingQuestion'), '');
  1177. }
  1178. echo '</a>';
  1179. echo '</div></li>';
  1180. echo '</ul>';
  1181. }
  1182. static function saveQuestionOption($question_id, $name, $course_id, $position = 0) {
  1183. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1184. $params['question_id'] = intval($question_id);
  1185. $params['name'] = $name;
  1186. $params['position'] = $position;
  1187. $params['c_id'] = $course_id;
  1188. $result = self::readQuestionOption($question_id, $course_id);
  1189. $last_id = Database::insert($TBL_EXERCICE_QUESTION_OPTION, $params);
  1190. return $last_id;
  1191. }
  1192. static function deleteAllQuestionOptions($question_id, $course_id) {
  1193. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1194. Database::delete($TBL_EXERCICE_QUESTION_OPTION, array('c_id = ? AND question_id = ?'=> array($course_id, $question_id)));
  1195. }
  1196. static function updateQuestionOption($id, $params, $course_id) {
  1197. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1198. $result = Database::update($TBL_EXERCICE_QUESTION_OPTION, $params, array('c_id = ? AND id = ?'=>array($course_id, $id)));
  1199. return $result;
  1200. }
  1201. static function readQuestionOption($question_id, $course_id) {
  1202. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1203. $result = Database::select('*', $TBL_EXERCICE_QUESTION_OPTION, array('where'=>array('c_id = ? AND question_id = ?' =>array($course_id, $question_id)), 'order'=>'id ASC'));
  1204. return $result;
  1205. }
  1206. function return_header($feedback_type = null, $counter = null) {
  1207. $counter_label = '';
  1208. if (!empty($counter)) {
  1209. $counter_label = intval($counter);
  1210. }
  1211. echo Display::div(get_lang("Question").' '.($counter_label).' : '.$this->question, array('id'=>'question_title', 'class'=>'sectiontitle'));
  1212. echo Display::div($this->description, array('id'=>'question_description'));
  1213. }
  1214. /**
  1215. * Create a question from a set of parameters
  1216. * @param int Quiz ID
  1217. * @param string Question name
  1218. * @param int Maximum result for the question
  1219. * @param int Type of question (see constants at beginning of question.class.php)
  1220. * @param int Question level/category
  1221. */
  1222. function create_question ($quiz_id, $question_name, $max_score = 0, $type = 1, $level = 1) {
  1223. $course_id = api_get_course_int_id();
  1224. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1225. $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1226. $quiz_id = filter_var($quiz_id,FILTER_SANITIZE_NUMBER_INT);
  1227. $max_score = filter_var($max_score,FILTER_SANITIZE_NUMBER_FLOAT);
  1228. $type = filter_var($type,FILTER_SANITIZE_NUMBER_INT);
  1229. $level = filter_var($level,FILTER_SANITIZE_NUMBER_INT);
  1230. // Get the max position
  1231. $sql = "SELECT max(position) as max_position"
  1232. ." FROM $tbl_quiz_question q INNER JOIN $tbl_quiz_rel_question r"
  1233. ." ON q.id = r.question_id"
  1234. ." AND exercice_id = $quiz_id AND q.c_id = $course_id AND r.c_id = $course_id";
  1235. $rs_max = Database::query($sql, __FILE__, __LINE__);
  1236. $row_max = Database::fetch_object($rs_max);
  1237. $max_position = $row_max->max_position +1;
  1238. // Insert the new question
  1239. $sql = "INSERT INTO $tbl_quiz_question"
  1240. ." (c_id, question,ponderation,position,type,level) "
  1241. ." VALUES($course_id, '".Database::escape_string($question_name)."',"
  1242. ." $max_score , $max_position, $type, $level)";
  1243. $rs = Database::query($sql);
  1244. // Get the question ID
  1245. $question_id = Database::get_last_insert_id();
  1246. // Get the max question_order
  1247. $sql = "SELECT max(question_order) as max_order "
  1248. ."FROM $tbl_quiz_rel_question WHERE c_id = $course_id AND exercice_id = $quiz_id ";
  1249. $rs_max_order = Database::query($sql);
  1250. $row_max_order = Database::fetch_object($rs_max_order);
  1251. $max_order = $row_max_order->max_order + 1;
  1252. // Attach questions to quiz
  1253. $sql = "INSERT INTO $tbl_quiz_rel_question "
  1254. ."(c_id, question_id,exercice_id,question_order)"
  1255. ." VALUES($course_id, $question_id, $quiz_id, $max_order)";
  1256. $rs = Database::query($sql);
  1257. return $question_id;
  1258. }
  1259. /**
  1260. * return the image filename of the question type
  1261. *
  1262. */
  1263. public function get_type_icon_html() {
  1264. $type = $this->selectType();
  1265. $tabQuestionList = Question::get_question_type_list(); // [0]=file to include [1]=type name
  1266. require_once $tabQuestionList[$type][0];
  1267. eval('$img = '.$tabQuestionList[$type][1].'::$typePicture;');
  1268. eval('$explanation = get_lang('.$tabQuestionList[$type][1].'::$explanationLangVar);');
  1269. return array($img, $explanation);
  1270. }
  1271. }
  1272. endif;