question.class.php 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  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");
  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;
  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;
  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);
  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);
  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. // 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. // question name
  1003. $form->addElement('text', 'questionName', get_lang('Question'), array('class' => 'span6'));
  1004. $form->addRule('questionName', get_lang('GiveQuestion'), 'required');
  1005. // default content
  1006. $isContent = isset($_REQUEST['isContent']) ? intval($_REQUEST['isContent']) : null;
  1007. // question type
  1008. $answerType= intval($_REQUEST['answerType']);
  1009. $form->addElement('hidden','answerType',$_REQUEST['answerType']);
  1010. // html editor
  1011. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  1012. if(is_array($fck_config)){
  1013. $editor_config = array_merge($editor_config, $fck_config);
  1014. }
  1015. if(!api_is_allowed_to_edit(null,true)) $editor_config['UserStatus'] = 'student';
  1016. $form->addElement('advanced_settings','
  1017. <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>
  1018. ');
  1019. $form -> addElement ('html','<div class="HideFCKEditor" id="HiddenFCKquestionDescription" >');
  1020. $form->add_html_editor('questionDescription', get_lang('langQuestionDescription'), false, false, $editor_config);
  1021. $form -> addElement ('html','</div>');
  1022. // Advanced parameters
  1023. $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>');
  1024. $select_level = array (1=>1,2=>2,3=>3,4=>4,5=>5);
  1025. $form->addElement('html','<div id="id_advancedOption" style="display:none;">');
  1026. $form->addElement('select', 'questionLevel',get_lang('Difficulty'), $select_level);
  1027. // categories
  1028. $tabCat = array();
  1029. $tabCat = Testcategory::getCategoriesIdAndName();
  1030. $form->addElement('select', 'questionCategory', get_lang('Category'), $tabCat);
  1031. // hidden values
  1032. $form->addElement('hidden','myid',$_REQUEST['myid']);
  1033. if (!isset($_GET['fromExercise'])) {
  1034. switch($answerType) {
  1035. case 1: $this->question = get_lang('langDefaultUniqueQuestion'); break;
  1036. case 2: $this->question = get_lang('langDefaultMultipleQuestion'); break;
  1037. case 3: $this->question = get_lang('langDefaultFillBlankQuestion'); break;
  1038. case 4: $this->question = get_lang('langDefaultMathingQuestion'); break;
  1039. case 5: $this->question = get_lang('langDefaultOpenQuestion'); break;
  1040. case 9: $this->question = get_lang('langDefaultMultipleQuestion'); break;
  1041. }
  1042. }
  1043. $form->addElement('html','</div>');
  1044. // default values
  1045. $defaults = array();
  1046. $defaults['questionName'] = $this -> question;
  1047. $defaults['questionDescription'] = $this -> description;
  1048. $defaults['questionLevel'] = $this -> level;
  1049. $defaults['questionCategory'] = $this->category;
  1050. //Came from he question pool
  1051. if (isset($_GET['fromExercise'])) {
  1052. $form->setDefaults($defaults);
  1053. }
  1054. if (!empty($_REQUEST['myid'])) {
  1055. $form->setDefaults($defaults);
  1056. } else {
  1057. if ($isContent == 1) {
  1058. $form->setDefaults($defaults);
  1059. }
  1060. }
  1061. }
  1062. /**
  1063. * function which process the creation of questions
  1064. * @param FormValidator $form the formvalidator instance
  1065. * @param Exercise $objExercise the Exercise instance
  1066. */
  1067. function processCreation ($form, $objExercise) {
  1068. $this -> updateTitle($form->getSubmitValue('questionName'));
  1069. $this -> updateDescription($form->getSubmitValue('questionDescription'));
  1070. $this -> updateLevel($form->getSubmitValue('questionLevel'));
  1071. $this->updateCategory($form->getSubmitValue('questionCategory'));
  1072. $this -> save($objExercise -> id);
  1073. // modify the exercise
  1074. $objExercise->addToList($this -> id);
  1075. $objExercise->update_question_positions();
  1076. }
  1077. /**
  1078. * abstract function which creates the form to create / edit the answers of the question
  1079. * @param the formvalidator instance
  1080. */
  1081. abstract function createAnswersForm ($form);
  1082. /**
  1083. * abstract function which process the creation of answers
  1084. * @param the formvalidator instance
  1085. */
  1086. abstract function processAnswersCreation ($form);
  1087. /**
  1088. * Displays the menu of question types
  1089. */
  1090. static function display_type_menu ($feedbacktype = 0) {
  1091. global $exerciseId;
  1092. $course_id = api_get_course_int_id();
  1093. // 1. by default we show all the question types
  1094. $question_type_custom_list = self::get_question_type_list();
  1095. if (!isset($feedbacktype)) $feedbacktype=0;
  1096. if ($feedbacktype==1) {
  1097. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  1098. //$question_type_custom_list = array ( UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER]);
  1099. $question_type_custom_list = array ( UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION]);
  1100. } else {
  1101. unset($question_type_custom_list[HOT_SPOT_DELINEATION]);
  1102. }
  1103. //blocking edition
  1104. $show_quiz_edition = true;
  1105. if (isset($exerciseId) && !empty($exerciseId)) {
  1106. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  1107. $sql="SELECT max_score FROM $TBL_LP_ITEM
  1108. WHERE c_id = $course_id AND item_type = '".TOOL_QUIZ."' AND path ='".Database::escape_string($exerciseId)."'";
  1109. $result = Database::query($sql);
  1110. if (Database::num_rows($result) > 0) {
  1111. $show_quiz_edition = false;
  1112. }
  1113. }
  1114. echo '<ul class="question_menu">';
  1115. foreach ($question_type_custom_list as $i=>$a_type) {
  1116. // include the class of the type
  1117. require_once($a_type[0]);
  1118. // get the picture of the type and the langvar which describes it
  1119. $img = $explanation = '';
  1120. eval('$img = '.$a_type[1].'::$typePicture;');
  1121. eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
  1122. echo '<li>';
  1123. echo '<div class="icon_image_content">';
  1124. if ($show_quiz_edition) {
  1125. echo '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.Display::return_icon($img, $explanation).'</a>';
  1126. //echo '<br>';
  1127. //echo '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.$explanation.'</a>';
  1128. } else {
  1129. $img = pathinfo($img);
  1130. $img = $img['filename'];
  1131. echo ''.Display::return_icon($img.'_na.gif',$explanation).'';
  1132. //echo '<br>';
  1133. //echo ''.$explanation.'';
  1134. }
  1135. echo '</div>';
  1136. echo '</li>';
  1137. }
  1138. echo '<li>';
  1139. echo '<div class="icon_image_content">';
  1140. if ($show_quiz_edition) {
  1141. if ($feedbacktype==1) {
  1142. echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&type=1&fromExercise='.$exerciseId.'">';
  1143. } else {
  1144. echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&fromExercise='.$exerciseId.'">';
  1145. }
  1146. echo Display::return_icon('database.png', get_lang('GetExistingQuestion'), '');
  1147. } else {
  1148. echo Display::return_icon('database_na.png', get_lang('GetExistingQuestion'), '');
  1149. }
  1150. echo '</a>';
  1151. echo '</div></li>';
  1152. echo '</ul>';
  1153. }
  1154. static function saveQuestionOption($question_id, $name, $course_id, $position = 0) {
  1155. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1156. $params['question_id'] = intval($question_id);
  1157. $params['name'] = $name;
  1158. $params['position'] = $position;
  1159. $params['c_id'] = $course_id;
  1160. $result = self::readQuestionOption($question_id, $course_id);
  1161. $last_id = Database::insert($TBL_EXERCICE_QUESTION_OPTION, $params);
  1162. return $last_id;
  1163. }
  1164. static function deleteAllQuestionOptions($question_id, $course_id) {
  1165. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1166. Database::delete($TBL_EXERCICE_QUESTION_OPTION, array('c_id = ? AND question_id = ?'=> array($course_id, $question_id)));
  1167. }
  1168. static function updateQuestionOption($id, $params, $course_id) {
  1169. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1170. $result = Database::update($TBL_EXERCICE_QUESTION_OPTION, $params, array('c_id = ? AND id = ?'=>array($course_id, $id)));
  1171. return $result;
  1172. }
  1173. static function readQuestionOption($question_id, $course_id) {
  1174. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1175. $result = Database::select('*', $TBL_EXERCICE_QUESTION_OPTION, array('where'=>array('c_id = ? AND question_id = ?' =>array($course_id, $question_id)), 'order'=>'id ASC'));
  1176. return $result;
  1177. }
  1178. function return_header($feedback_type = null, $counter = null) {
  1179. $counter_label = '';
  1180. if (!empty($counter)) {
  1181. $counter_label = intval($counter);
  1182. }
  1183. echo Display::div(get_lang("Question").' '.($counter_label).' : '.$this->question, array('id'=>'question_title', 'class'=>'sectiontitle'));
  1184. echo Display::div($this->description, array('id'=>'question_description'));
  1185. }
  1186. /**
  1187. * Create a question from a set of parameters
  1188. * @param int Quiz ID
  1189. * @param string Question name
  1190. * @param int Maximum result for the question
  1191. * @param int Type of question (see constants at beginning of question.class.php)
  1192. * @param int Question level/category
  1193. */
  1194. function create_question ($quiz_id, $question_name, $max_score = 0, $type = 1, $level = 1) {
  1195. $course_id = api_get_course_int_id();
  1196. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1197. $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1198. $quiz_id = filter_var($quiz_id,FILTER_SANITIZE_NUMBER_INT);
  1199. $max_score = filter_var($max_score,FILTER_SANITIZE_NUMBER_FLOAT);
  1200. $type = filter_var($type,FILTER_SANITIZE_NUMBER_INT);
  1201. $level = filter_var($level,FILTER_SANITIZE_NUMBER_INT);
  1202. // Get the max position
  1203. $sql = "SELECT max(position) as max_position"
  1204. ." FROM $tbl_quiz_question q INNER JOIN $tbl_quiz_rel_question r"
  1205. ." ON q.id = r.question_id"
  1206. ." AND exercice_id = $quiz_id AND q.c_id = $course_id AND r.c_id = $course_id";
  1207. $rs_max = Database::query($sql, __FILE__, __LINE__);
  1208. $row_max = Database::fetch_object($rs_max);
  1209. $max_position = $row_max->max_position +1;
  1210. // Insert the new question
  1211. $sql = "INSERT INTO $tbl_quiz_question"
  1212. ." (c_id, question,ponderation,position,type,level) "
  1213. ." VALUES($course_id, '".Database::escape_string($question_name)."',"
  1214. ." $max_score , $max_position, $type, $level)";
  1215. $rs = Database::query($sql);
  1216. // Get the question ID
  1217. $question_id = Database::get_last_insert_id();
  1218. // Get the max question_order
  1219. $sql = "SELECT max(question_order) as max_order "
  1220. ."FROM $tbl_quiz_rel_question WHERE c_id = $course_id AND exercice_id = $quiz_id ";
  1221. $rs_max_order = Database::query($sql);
  1222. $row_max_order = Database::fetch_object($rs_max_order);
  1223. $max_order = $row_max_order->max_order + 1;
  1224. // Attach questions to quiz
  1225. $sql = "INSERT INTO $tbl_quiz_rel_question "
  1226. ."(c_id, question_id,exercice_id,question_order)"
  1227. ." VALUES($course_id, $question_id, $quiz_id, $max_order)";
  1228. $rs = Database::query($sql);
  1229. return $question_id;
  1230. }
  1231. /**
  1232. * return the image filename of the question type
  1233. *
  1234. */
  1235. public function get_type_icon_html() {
  1236. $type = $this->selectType();
  1237. $tabQuestionList = Question::get_question_type_list(); // [0]=file to include [1]=type name
  1238. require_once $tabQuestionList[$type][0];
  1239. eval('$img = '.$tabQuestionList[$type][1].'::$typePicture;');
  1240. eval('$explanation = get_lang('.$tabQuestionList[$type][1].'::$explanationLangVar);');
  1241. return array($img, $explanation);
  1242. }
  1243. }
  1244. endif;