question.class.php 68 KB

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