question.class.php 62 KB

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