question.class.php 55 KB

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