question.class.php 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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 false;
  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. $id = $this->id;
  721. $question = $this->question;
  722. $description = $this->description;
  723. $weighting = $this->weighting;
  724. $position = $this->position;
  725. $type = $this->type;
  726. $picture = $this->picture;
  727. $level = $this->level;
  728. $extra = $this->extra;
  729. $c_id = $this->course['real_id'];
  730. $category = $this->category;
  731. // question already exists
  732. if(!empty($id)) {
  733. $params = [
  734. 'question' => $question,
  735. 'description' => $description,
  736. 'ponderation' => $weighting,
  737. 'position' => $position,
  738. 'type' => $type,
  739. 'picture' => $picture,
  740. 'extra' => $extra,
  741. 'level' => $level,
  742. ];
  743. Database::update(
  744. $TBL_QUESTIONS,
  745. $params,
  746. ['c_id = ? AND id = ?' => [$c_id, $id]]
  747. );
  748. $this->saveCategory($category);
  749. if (!empty($exerciseId)) {
  750. api_item_property_update(
  751. $this->course,
  752. TOOL_QUIZ,
  753. $id,
  754. 'QuizQuestionUpdated',
  755. api_get_user_id()
  756. );
  757. }
  758. if (api_get_setting('search_enabled') == 'true') {
  759. if ($exerciseId != 0) {
  760. $this -> search_engine_edit($exerciseId);
  761. } else {
  762. /**
  763. * actually there is *not* an user interface for
  764. * creating questions without a relation with an exercise
  765. */
  766. }
  767. }
  768. } else {
  769. // creates a new question
  770. $sql = "SELECT max(position)
  771. FROM $TBL_QUESTIONS as question,
  772. $TBL_EXERCISE_QUESTION as test_question
  773. WHERE
  774. question.id = test_question.question_id AND
  775. test_question.exercice_id = " . intval($exerciseId) . " AND
  776. question.c_id = $c_id AND
  777. test_question.c_id = $c_id ";
  778. $result = Database::query($sql);
  779. $current_position = Database::result($result,0,0);
  780. $this->updatePosition($current_position+1);
  781. $position = $this->position;
  782. $params = [
  783. 'c_id' => $c_id,
  784. 'question' => $question,
  785. 'description' => $description,
  786. 'ponderation' => $weighting,
  787. 'position' => $position,
  788. 'type' => $type,
  789. 'picture' => $picture,
  790. 'extra' => $extra,
  791. 'level' => $level
  792. ];
  793. $this->id = Database::insert($TBL_QUESTIONS, $params);
  794. if ($this->id) {
  795. $sql = "UPDATE $TBL_QUESTIONS SET id = iid WHERE iid = {$this->id}";
  796. Database::query($sql);
  797. api_item_property_update(
  798. $this->course,
  799. TOOL_QUIZ,
  800. $this->id,
  801. 'QuizQuestionAdded',
  802. api_get_user_id()
  803. );
  804. // If hotspot, create first answer
  805. if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) {
  806. $TBL_ANSWERS = Database::get_course_table(
  807. TABLE_QUIZ_ANSWER
  808. );
  809. $params = [
  810. 'c_id' => $c_id,
  811. 'question_id' => $this->id,
  812. 'answer' => '',
  813. 'correct' => '',
  814. 'comment' => '',
  815. 'ponderation' => 10,
  816. 'position' => 1,
  817. 'hotspot_coordinates' => '0;0|0|0',
  818. 'hotspot_type' => 'square',
  819. ];
  820. $id = Database::insert($TBL_ANSWERS, $params);
  821. if ($id) {
  822. $sql = "UPDATE $TBL_ANSWERS SET id = iid, id_auto = iid WHERE iid = $id";
  823. Database::query($sql);
  824. }
  825. }
  826. if ($type == HOT_SPOT_DELINEATION) {
  827. $TBL_ANSWERS = Database::get_course_table(
  828. TABLE_QUIZ_ANSWER
  829. );
  830. $params = [
  831. 'c_id' => $c_id,
  832. 'question_id' => $this->id,
  833. 'answer' => '',
  834. 'correct' => '',
  835. 'comment' => '',
  836. 'ponderation' => 10,
  837. 'position' => 1,
  838. 'hotspot_coordinates' => '0;0|0|0',
  839. 'hotspot_type' => 'delineation',
  840. ];
  841. $id = Database::insert($TBL_ANSWERS, $params);
  842. if ($id) {
  843. $sql = "UPDATE $TBL_ANSWERS SET id = iid, id_auto = iid WHERE iid = $id";
  844. Database::query($sql);
  845. }
  846. }
  847. if (api_get_setting('search_enabled') == 'true') {
  848. if ($exerciseId != 0) {
  849. $this->search_engine_edit($exerciseId, true);
  850. } else {
  851. /**
  852. * actually there is *not* an user interface for
  853. * creating questions without a relation with an exercise
  854. */
  855. }
  856. }
  857. }
  858. }
  859. // if the question is created in an exercise
  860. if ($exerciseId) {
  861. // adds the exercise into the exercise list of this question
  862. $this->addToList($exerciseId, TRUE);
  863. }
  864. }
  865. public function search_engine_edit($exerciseId, $addQs=false, $rmQs=false)
  866. {
  867. // update search engine and its values table if enabled
  868. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  869. $course_id = api_get_course_id();
  870. // get search_did
  871. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  872. if ($addQs || $rmQs) {
  873. //there's only one row per question on normal db and one document per question on search engine db
  874. $sql = 'SELECT * FROM %s
  875. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
  876. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  877. } else {
  878. $sql = 'SELECT * FROM %s
  879. WHERE course_code=\'%s\' AND tool_id=\'%s\'
  880. AND ref_id_high_level=%s AND ref_id_second_level=%s LIMIT 1';
  881. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  882. }
  883. $res = Database::query($sql);
  884. if (Database::num_rows($res) > 0 || $addQs) {
  885. require_once(api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php');
  886. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  887. $di = new ChamiloIndexer();
  888. if ($addQs) {
  889. $question_exercises = array((int) $exerciseId);
  890. } else {
  891. $question_exercises = array();
  892. }
  893. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  894. $di->connectDb(NULL, NULL, $lang);
  895. // retrieve others exercise ids
  896. $se_ref = Database::fetch_array($res);
  897. $se_doc = $di->get_document((int)$se_ref['search_did']);
  898. if ($se_doc !== FALSE) {
  899. if (($se_doc_data = $di->get_document_data($se_doc)) !== FALSE) {
  900. $se_doc_data = unserialize($se_doc_data);
  901. if (
  902. isset($se_doc_data[SE_DATA]['type']) &&
  903. $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION
  904. ) {
  905. if (
  906. isset($se_doc_data[SE_DATA]['exercise_ids']) &&
  907. is_array($se_doc_data[SE_DATA]['exercise_ids'])
  908. ) {
  909. foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
  910. if (!in_array($old_value, $question_exercises)) {
  911. $question_exercises[] = $old_value;
  912. }
  913. }
  914. }
  915. }
  916. }
  917. }
  918. if ($rmQs) {
  919. while (($key = array_search($exerciseId, $question_exercises)) !== FALSE) {
  920. unset($question_exercises[$key]);
  921. }
  922. }
  923. // build the chunk to index
  924. $ic_slide = new IndexableChunk();
  925. $ic_slide->addValue("title", $this->question);
  926. $ic_slide->addCourseId($course_id);
  927. $ic_slide->addToolId(TOOL_QUIZ);
  928. $xapian_data = array(
  929. SE_COURSE_ID => $course_id,
  930. SE_TOOL_ID => TOOL_QUIZ,
  931. SE_DATA => array(
  932. 'type' => SE_DOCTYPE_EXERCISE_QUESTION,
  933. 'exercise_ids' => $question_exercises,
  934. 'question_id' => (int)$this->id
  935. ),
  936. SE_USER => (int)api_get_user_id(),
  937. );
  938. $ic_slide->xapian_data = serialize($xapian_data);
  939. $ic_slide->addValue("content", $this->description);
  940. //TODO: index answers, see also form validation on question_admin.inc.php
  941. $di->remove_document((int)$se_ref['search_did']);
  942. $di->addChunk($ic_slide);
  943. //index and return search engine document id
  944. if (!empty($question_exercises)) { // if empty there is nothing to index
  945. $did = $di->index();
  946. unset($di);
  947. }
  948. if ($did || $rmQs) {
  949. // save it to db
  950. if ($addQs || $rmQs) {
  951. $sql = "DELETE FROM %s
  952. WHERE course_code = '%s' AND tool_id = '%s' AND ref_id_second_level = '%s'";
  953. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  954. } else {
  955. $sql = "DELETE FROM %S
  956. WHERE
  957. course_code = '%s'
  958. AND tool_id = '%s'
  959. AND tool_id = '%s'
  960. AND ref_id_high_level = '%s'
  961. AND ref_id_second_level = '%s'";
  962. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  963. }
  964. Database::query($sql);
  965. if ($rmQs) {
  966. if (!empty($question_exercises)) {
  967. $sql = "INSERT INTO %s (
  968. id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
  969. )
  970. VALUES (
  971. NULL, '%s', '%s', %s, %s, %s
  972. )";
  973. $sql = sprintf(
  974. $sql,
  975. $tbl_se_ref,
  976. $course_id,
  977. TOOL_QUIZ,
  978. array_shift($question_exercises),
  979. $this->id,
  980. $did
  981. );
  982. Database::query($sql);
  983. }
  984. } else {
  985. $sql = "INSERT INTO %s (
  986. id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
  987. )
  988. VALUES (
  989. NULL , '%s', '%s', %s, %s, %s
  990. )";
  991. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
  992. Database::query($sql);
  993. }
  994. }
  995. }
  996. }
  997. }
  998. /**
  999. * adds an exercise into the exercise list
  1000. *
  1001. * @author Olivier Brouckaert
  1002. * @param integer $exerciseId - exercise ID
  1003. * @param boolean $fromSave - from $this->save() or not
  1004. */
  1005. public function addToList($exerciseId, $fromSave = false)
  1006. {
  1007. $exerciseRelQuestionTable = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1008. $id = $this->id;
  1009. // checks if the exercise ID is not in the list
  1010. if (!in_array($exerciseId, $this->exerciseList)) {
  1011. $this->exerciseList[] = $exerciseId;
  1012. $new_exercise = new Exercise();
  1013. $new_exercise->read($exerciseId);
  1014. $count = $new_exercise->selectNbrQuestions();
  1015. $count++;
  1016. $sql = "INSERT INTO $exerciseRelQuestionTable (c_id, question_id, exercice_id, question_order)
  1017. VALUES ({$this->course['real_id']}, " . intval($id) . ", " . intval($exerciseId) . ", '$count')";
  1018. Database::query($sql);
  1019. // we do not want to reindex if we had just saved adnd indexed the question
  1020. if (!$fromSave) {
  1021. $this->search_engine_edit($exerciseId, TRUE);
  1022. }
  1023. }
  1024. }
  1025. /**
  1026. * removes an exercise from the exercise list
  1027. *
  1028. * @author Olivier Brouckaert
  1029. * @param integer $exerciseId - exercise ID
  1030. * @return boolean - true if removed, otherwise false
  1031. */
  1032. function removeFromList($exerciseId)
  1033. {
  1034. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1035. $id = $this->id;
  1036. // searches the position of the exercise ID in the list
  1037. $pos = array_search($exerciseId, $this->exerciseList);
  1038. $course_id = api_get_course_int_id();
  1039. // exercise not found
  1040. if($pos === false) {
  1041. return false;
  1042. } else {
  1043. // deletes the position in the array containing the wanted exercise ID
  1044. unset($this->exerciseList[$pos]);
  1045. //update order of other elements
  1046. $sql = "SELECT question_order
  1047. FROM $TBL_EXERCISE_QUESTION
  1048. WHERE
  1049. c_id = $course_id
  1050. AND question_id = " . intval($id) . "
  1051. AND exercice_id = " . intval($exerciseId);
  1052. $res = Database::query($sql);
  1053. if (Database::num_rows($res)>0) {
  1054. $row = Database::fetch_array($res);
  1055. if (!empty($row['question_order'])) {
  1056. $sql = "UPDATE $TBL_EXERCISE_QUESTION
  1057. SET question_order = question_order-1
  1058. WHERE
  1059. c_id = $course_id
  1060. AND exercice_id = " . intval($exerciseId) . "
  1061. AND question_order > " . $row['question_order'];
  1062. Database::query($sql);
  1063. }
  1064. }
  1065. $sql = "DELETE FROM $TBL_EXERCISE_QUESTION
  1066. WHERE
  1067. c_id = $course_id
  1068. AND question_id = " . intval($id) . "
  1069. AND exercice_id = " . intval($exerciseId);
  1070. Database::query($sql);
  1071. return true;
  1072. }
  1073. }
  1074. /**
  1075. * Deletes a question from the database
  1076. * the parameter tells if the question is removed from all exercises (value = 0),
  1077. * or just from one exercise (value = exercise ID)
  1078. *
  1079. * @author Olivier Brouckaert
  1080. * @param integer $deleteFromEx - exercise ID if the question is only removed from one exercise
  1081. */
  1082. public function delete($deleteFromEx = 0)
  1083. {
  1084. $course_id = api_get_course_int_id();
  1085. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1086. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1087. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  1088. $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  1089. $id = intval($this->id);
  1090. // if the question must be removed from all exercises
  1091. if (!$deleteFromEx) {
  1092. //update the question_order of each question to avoid inconsistencies
  1093. $sql = "SELECT exercice_id, question_order FROM $TBL_EXERCISE_QUESTION
  1094. WHERE c_id = $course_id AND question_id = ".intval($id)."";
  1095. $res = Database::query($sql);
  1096. if (Database::num_rows($res) > 0) {
  1097. while ($row = Database::fetch_array($res)) {
  1098. if (!empty($row['question_order'])) {
  1099. $sql = "UPDATE $TBL_EXERCISE_QUESTION
  1100. SET question_order = question_order-1
  1101. WHERE
  1102. c_id= $course_id
  1103. AND exercice_id = " . intval($row['exercice_id']) . "
  1104. AND question_order > " . $row['question_order'];
  1105. Database::query($sql);
  1106. }
  1107. }
  1108. }
  1109. $sql = "DELETE FROM $TBL_EXERCISE_QUESTION
  1110. WHERE c_id = $course_id AND question_id = " . $id;
  1111. Database::query($sql);
  1112. $sql = "DELETE FROM $TBL_QUESTIONS
  1113. WHERE c_id = $course_id AND id = " . $id;
  1114. Database::query($sql);
  1115. $sql = "DELETE FROM $TBL_REPONSES
  1116. WHERE c_id = $course_id AND question_id = " . $id;
  1117. Database::query($sql);
  1118. // remove the category of this question in the question_rel_category table
  1119. $sql = "DELETE FROM $TBL_QUIZ_QUESTION_REL_CATEGORY
  1120. WHERE
  1121. c_id = $course_id AND
  1122. question_id = " . $id;
  1123. Database::query($sql);
  1124. api_item_property_update(
  1125. $this->course,
  1126. TOOL_QUIZ,
  1127. $id,
  1128. 'QuizQuestionDeleted',
  1129. api_get_user_id()
  1130. );
  1131. $this->removePicture();
  1132. } else {
  1133. // just removes the exercise from the list
  1134. $this->removeFromList($deleteFromEx);
  1135. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1136. // disassociate question with this exercise
  1137. $this->search_engine_edit($deleteFromEx, FALSE, TRUE);
  1138. }
  1139. api_item_property_update(
  1140. $this->course,
  1141. TOOL_QUIZ,
  1142. $id,
  1143. 'QuizQuestionDeleted',
  1144. api_get_user_id()
  1145. );
  1146. }
  1147. }
  1148. /**
  1149. * Duplicates the question
  1150. *
  1151. * @author Olivier Brouckaert
  1152. * @param array $course_info Course info of the destination course
  1153. * @return false|string ID of the new question
  1154. */
  1155. public function duplicate($course_info = [])
  1156. {
  1157. if (empty($course_info)) {
  1158. $course_info = $this->course;
  1159. } else {
  1160. $course_info = $course_info;
  1161. }
  1162. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1163. $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1164. $question = $this->question;
  1165. $description = $this->description;
  1166. $weighting = $this->weighting;
  1167. $position = $this->position;
  1168. $type = $this->type;
  1169. $level = intval($this->level);
  1170. $extra = $this->extra;
  1171. //Using the same method used in the course copy to transform URLs
  1172. if ($this->course['id'] != $course_info['id']) {
  1173. $description = DocumentManager::replace_urls_inside_content_html_from_copy_course(
  1174. $description,
  1175. $this->course['code'],
  1176. $course_info['id']
  1177. );
  1178. $question = DocumentManager::replace_urls_inside_content_html_from_copy_course(
  1179. $question,
  1180. $this->course['code'],
  1181. $course_info['id']
  1182. );
  1183. }
  1184. $course_id = $course_info['real_id'];
  1185. //Read the source options
  1186. $options = self::readQuestionOption($this->id, $this->course['real_id']);
  1187. // Inserting in the new course db / or the same course db
  1188. $params = [
  1189. 'c_id' => $course_id,
  1190. 'question' => $question,
  1191. 'description' => $description,
  1192. 'ponderation' => $weighting,
  1193. 'position' => $position,
  1194. 'type' => $type,
  1195. 'level' => $level,
  1196. 'extra' => $extra
  1197. ];
  1198. $new_question_id = Database::insert($TBL_QUESTIONS, $params);
  1199. if ($new_question_id) {
  1200. $sql = "UPDATE $TBL_QUESTIONS SET id = iid
  1201. WHERE iid = $new_question_id";
  1202. Database::query($sql);
  1203. if (!empty($options)) {
  1204. //Saving the quiz_options
  1205. foreach ($options as $item) {
  1206. $item['question_id'] = $new_question_id;
  1207. $item['c_id'] = $course_id;
  1208. unset($item['id']);
  1209. unset($item['iid']);
  1210. $id = Database::insert($TBL_QUESTION_OPTIONS, $item);
  1211. if ($id) {
  1212. $sql = "UPDATE $TBL_QUESTION_OPTIONS SET id = iid
  1213. WHERE iid = $id";
  1214. Database::query($sql);
  1215. }
  1216. }
  1217. }
  1218. // Duplicates the picture of the hotspot
  1219. $this->exportPicture($new_question_id, $course_info);
  1220. }
  1221. return $new_question_id;
  1222. }
  1223. /**
  1224. * @return string
  1225. */
  1226. public function get_question_type_name()
  1227. {
  1228. $key = self::$questionTypes[$this->type];
  1229. return get_lang($key[1]);
  1230. }
  1231. /**
  1232. * @param string $type
  1233. * @return null
  1234. */
  1235. public static function get_question_type($type)
  1236. {
  1237. if ($type == ORAL_EXPRESSION && api_get_setting('enable_nanogong') != 'true') {
  1238. return null;
  1239. }
  1240. return self::$questionTypes[$type];
  1241. }
  1242. /**
  1243. * @return array
  1244. */
  1245. public static function get_question_type_list()
  1246. {
  1247. if (api_get_setting('enable_nanogong') != 'true') {
  1248. self::$questionTypes[ORAL_EXPRESSION] = null;
  1249. unset(self::$questionTypes[ORAL_EXPRESSION]);
  1250. }
  1251. if (api_get_setting('enable_quiz_scenario') !== 'true') {
  1252. self::$questionTypes[HOT_SPOT_DELINEATION] = null;
  1253. unset(self::$questionTypes[HOT_SPOT_DELINEATION]);
  1254. }
  1255. return self::$questionTypes;
  1256. }
  1257. /**
  1258. * Returns an instance of the class corresponding to the type
  1259. * @param integer $type the type of the question
  1260. * @return $this instance of a Question subclass (or of Questionc class by default)
  1261. */
  1262. public static function getInstance($type)
  1263. {
  1264. if (!is_null($type)) {
  1265. list($file_name, $class_name) = self::get_question_type($type);
  1266. if (!empty($file_name)) {
  1267. include_once $file_name;
  1268. if (class_exists($class_name)) {
  1269. return new $class_name();
  1270. } else {
  1271. echo 'Can\'t instanciate class ' . $class_name . ' of type ' . $type;
  1272. }
  1273. }
  1274. }
  1275. return null;
  1276. }
  1277. /**
  1278. * Creates the form to create / edit a question
  1279. * A subclass can redefine this function to add fields...
  1280. * @param FormValidator $form
  1281. */
  1282. public function createForm(&$form)
  1283. {
  1284. echo '<style>
  1285. .media { display:none;}
  1286. </style>';
  1287. echo '<script>
  1288. // hack to hide http://cksource.com/forums/viewtopic.php?f=6&t=8700
  1289. function FCKeditor_OnComplete( editorInstance ) {
  1290. if (document.getElementById ( \'HiddenFCK\' + editorInstance.Name)) {
  1291. HideFCKEditorByInstanceName (editorInstance.Name);
  1292. }
  1293. }
  1294. function HideFCKEditorByInstanceName ( editorInstanceName ) {
  1295. if (document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className == "HideFCKEditor" ) {
  1296. document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className = "media";
  1297. }
  1298. }
  1299. </script>';
  1300. // question name
  1301. $form->addElement('text', 'questionName', get_lang('Question'));
  1302. $form->addRule('questionName', get_lang('GiveQuestion'), 'required');
  1303. // default content
  1304. $isContent = isset($_REQUEST['isContent']) ? intval($_REQUEST['isContent']) : null;
  1305. // Question type
  1306. $answerType = isset($_REQUEST['answerType']) ? intval($_REQUEST['answerType']) : null;
  1307. $form->addElement('hidden','answerType', $answerType);
  1308. // html editor
  1309. $editorConfig = array(
  1310. 'ToolbarSet' => 'TestQuestionDescription',
  1311. 'Height' => '150'
  1312. );
  1313. if (!api_is_allowed_to_edit(null,true)) {
  1314. $editorConfig['UserStatus'] = 'student';
  1315. }
  1316. $form->addButtonAdvancedSettings('advanced_params');
  1317. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  1318. $form->addHtmlEditor('questionDescription', get_lang('QuestionDescription'), false, false, $editorConfig);
  1319. // hidden values
  1320. $my_id = isset($_REQUEST['myid']) ? intval($_REQUEST['myid']) : null;
  1321. $form->addElement('hidden', 'myid', $my_id);
  1322. if ($this->type != MEDIA_QUESTION) {
  1323. // Advanced parameters
  1324. $select_level = Question::get_default_levels();
  1325. $form->addElement('select', 'questionLevel', get_lang('Difficulty'), $select_level);
  1326. // Categories
  1327. $tabCat = TestCategory::getCategoriesIdAndName();
  1328. $form->addElement('select', 'questionCategory', get_lang('Category'), $tabCat);
  1329. switch ($this->type) {
  1330. case UNIQUE_ANSWER:
  1331. $form->addButton('convertAnswer', get_lang('ConvertToMultipleAnswer'), 'dot-circle-o', 'info');
  1332. break;
  1333. case MULTIPLE_ANSWER:
  1334. $form->addButton('convertAnswer', get_lang('ConvertToUniqueAnswer'), 'check-square-o', 'info');
  1335. break;
  1336. }
  1337. //Medias
  1338. //$course_medias = Question::prepare_course_media_select(api_get_course_int_id());
  1339. //$form->addElement('select', 'parent_id', get_lang('AttachToMedia'), $course_medias);
  1340. }
  1341. $form->addElement('html', '</div>');
  1342. if (!isset($_GET['fromExercise'])) {
  1343. switch ($answerType) {
  1344. case 1:
  1345. $this->question = get_lang('DefaultUniqueQuestion');
  1346. break;
  1347. case 2:
  1348. $this->question = get_lang('DefaultMultipleQuestion');
  1349. break;
  1350. case 3:
  1351. $this->question = get_lang('DefaultFillBlankQuestion');
  1352. break;
  1353. case 4:
  1354. $this->question = get_lang('DefaultMathingQuestion');
  1355. break;
  1356. case 5:
  1357. $this->question = get_lang('DefaultOpenQuestion');
  1358. break;
  1359. case 9:
  1360. $this->question = get_lang('DefaultMultipleQuestion');
  1361. break;
  1362. }
  1363. }
  1364. // default values
  1365. $defaults = array();
  1366. $defaults['questionName'] = $this->question;
  1367. $defaults['questionDescription'] = $this->description;
  1368. $defaults['questionLevel'] = $this->level;
  1369. $defaults['questionCategory'] = $this->category;
  1370. // Came from he question pool
  1371. if (isset($_GET['fromExercise'])) {
  1372. $form->setDefaults($defaults);
  1373. }
  1374. if (!empty($_REQUEST['myid'])) {
  1375. $form->setDefaults($defaults);
  1376. } else {
  1377. if ($isContent == 1) {
  1378. $form->setDefaults($defaults);
  1379. }
  1380. }
  1381. }
  1382. /**
  1383. * function which process the creation of questions
  1384. * @param FormValidator $form
  1385. * @param Exercise $objExercise
  1386. */
  1387. public function processCreation($form, $objExercise = null)
  1388. {
  1389. $this->updateTitle($form->getSubmitValue('questionName'));
  1390. $this->updateDescription($form->getSubmitValue('questionDescription'));
  1391. $this->updateLevel($form->getSubmitValue('questionLevel'));
  1392. $this->updateCategory($form->getSubmitValue('questionCategory'));
  1393. //Save normal question if NOT media
  1394. if ($this->type != MEDIA_QUESTION) {
  1395. $this->save($objExercise->id);
  1396. // modify the exercise
  1397. $objExercise->addToList($this->id);
  1398. $objExercise->update_question_positions();
  1399. }
  1400. }
  1401. /**
  1402. * abstract function which creates the form to create / edit the answers of the question
  1403. * @param the FormValidator instance
  1404. */
  1405. abstract function createAnswersForm($form);
  1406. /**
  1407. * abstract function which process the creation of answers
  1408. * @param the FormValidator instance
  1409. */
  1410. abstract function processAnswersCreation($form);
  1411. /**
  1412. * Displays the menu of question types
  1413. *
  1414. * @param Exercise $objExercise
  1415. */
  1416. public static function display_type_menu($objExercise)
  1417. {
  1418. $feedback_type = $objExercise->feedback_type;
  1419. $exerciseId = $objExercise->id;
  1420. // 1. by default we show all the question types
  1421. $question_type_custom_list = self::get_question_type_list();
  1422. if (!isset($feedback_type)) {
  1423. $feedback_type = 0;
  1424. }
  1425. if ($feedback_type == 1) {
  1426. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  1427. $question_type_custom_list = array (
  1428. UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],
  1429. HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION]
  1430. );
  1431. } else {
  1432. unset($question_type_custom_list[HOT_SPOT_DELINEATION]);
  1433. }
  1434. echo '<div class="well">';
  1435. echo '<ul class="question_menu">';
  1436. foreach ($question_type_custom_list as $i => $a_type) {
  1437. // include the class of the type
  1438. require_once $a_type[0];
  1439. // get the picture of the type and the langvar which describes it
  1440. $img = $explanation = '';
  1441. eval('$img = ' . $a_type[1] . '::$typePicture;');
  1442. eval('$explanation = get_lang(' . $a_type[1] . '::$explanationLangVar);');
  1443. echo '<li>';
  1444. echo '<div class="icon-image">';
  1445. if ($objExercise->exercise_was_added_in_lp == true) {
  1446. $img = pathinfo($img);
  1447. $img = $img['filename'] . '_na.' . $img['extension'];
  1448. echo Display::return_icon($img, $explanation, null, ICON_SIZE_BIG);
  1449. } else {
  1450. echo '<a href="admin.php?' . api_get_cidreq() . '&newQuestion=yes&answerType=' . $i . '">' .
  1451. Display::return_icon($img, $explanation, null, ICON_SIZE_BIG) . '</a>';
  1452. }
  1453. echo '</div>';
  1454. echo '</li>';
  1455. }
  1456. echo '<li>';
  1457. echo '<div class="icon_image_content">';
  1458. if ($objExercise->exercise_was_added_in_lp == true) {
  1459. echo Display::return_icon('database_na.png', get_lang('GetExistingQuestion'), null, ICON_SIZE_BIG);
  1460. } else {
  1461. if ($feedback_type == 1) {
  1462. echo $url = "<a href=\"question_pool.php?" . api_get_cidreq() . "&type=1&fromExercise=$exerciseId\">";
  1463. } else {
  1464. echo $url = '<a href="question_pool.php?' . api_get_cidreq() . '&fromExercise=' . $exerciseId . '">';
  1465. }
  1466. echo Display::return_icon('database.png', get_lang('GetExistingQuestion'), null, ICON_SIZE_BIG);
  1467. }
  1468. echo '</a>';
  1469. echo '</div></li>';
  1470. echo '</ul>';
  1471. echo '</div>';
  1472. }
  1473. /**
  1474. * @param int $question_id
  1475. * @param string $name
  1476. * @param int $course_id
  1477. * @param int $position
  1478. * @return false|string
  1479. */
  1480. static function saveQuestionOption($question_id, $name, $course_id, $position = 0)
  1481. {
  1482. $TBL_EXERCISE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1483. $params['question_id'] = intval($question_id);
  1484. $params['name'] = $name;
  1485. $params['position'] = $position;
  1486. $params['c_id'] = $course_id;
  1487. $result = self::readQuestionOption($question_id, $course_id);
  1488. $last_id = Database::insert($TBL_EXERCISE_QUESTION_OPTION, $params);
  1489. if ($last_id) {
  1490. $sql = "UPDATE $TBL_EXERCISE_QUESTION_OPTION SET id = iid WHERE iid = $last_id";
  1491. Database::query($sql);
  1492. }
  1493. return $last_id;
  1494. }
  1495. /**
  1496. * @param int $question_id
  1497. * @param int $course_id
  1498. */
  1499. static function deleteAllQuestionOptions($question_id, $course_id)
  1500. {
  1501. $TBL_EXERCISE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1502. Database::delete(
  1503. $TBL_EXERCISE_QUESTION_OPTION,
  1504. array(
  1505. 'c_id = ? AND question_id = ?' => array(
  1506. $course_id,
  1507. $question_id
  1508. )
  1509. )
  1510. );
  1511. }
  1512. /**
  1513. * @param int $id
  1514. * @param array $params
  1515. * @param int $course_id
  1516. * @return bool|int
  1517. */
  1518. static function updateQuestionOption($id, $params, $course_id)
  1519. {
  1520. $TBL_EXERCISE_QUESTION_OPTION = Database::get_course_table(
  1521. TABLE_QUIZ_QUESTION_OPTION
  1522. );
  1523. $result = Database::update(
  1524. $TBL_EXERCISE_QUESTION_OPTION,
  1525. $params,
  1526. array('c_id = ? AND id = ?' => array($course_id, $id))
  1527. );
  1528. return $result;
  1529. }
  1530. /**
  1531. * @param int $question_id
  1532. * @param int $course_id
  1533. * @return array
  1534. */
  1535. static function readQuestionOption($question_id, $course_id)
  1536. {
  1537. $TBL_EXERCISE_QUESTION_OPTION = Database::get_course_table(
  1538. TABLE_QUIZ_QUESTION_OPTION
  1539. );
  1540. $result = Database::select(
  1541. '*',
  1542. $TBL_EXERCISE_QUESTION_OPTION,
  1543. array(
  1544. 'where' => array(
  1545. 'c_id = ? AND question_id = ?' => array(
  1546. $course_id,
  1547. $question_id
  1548. )
  1549. ),
  1550. 'order' => 'id ASC'
  1551. )
  1552. );
  1553. return $result;
  1554. }
  1555. /**
  1556. * Shows question title an description
  1557. *
  1558. * @param string $feedback_type
  1559. * @param int $counter
  1560. * @param float $score
  1561. */
  1562. function return_header($feedback_type = null, $counter = null, $score = null)
  1563. {
  1564. $counter_label = '';
  1565. if (!empty($counter)) {
  1566. $counter_label = intval($counter);
  1567. }
  1568. $score_label = get_lang('Wrong');
  1569. $class = 'error';
  1570. if ($score['pass'] == true) {
  1571. $score_label = get_lang('Correct');
  1572. $class = 'success';
  1573. }
  1574. if ($this->type == FREE_ANSWER || $this->type == ORAL_EXPRESSION) {
  1575. $score['revised'] = isset($score['revised']) ? $score['revised'] : false;
  1576. if ($score['revised'] == true) {
  1577. $score_label = get_lang('Revised');
  1578. $class = '';
  1579. } else {
  1580. $score_label = get_lang('NotRevised');
  1581. $class = 'error';
  1582. }
  1583. }
  1584. $question_title = $this->question;
  1585. // display question category, if any
  1586. $header = TestCategory::returnCategoryAndTitle($this->id);
  1587. $show_media = null;
  1588. if ($show_media) {
  1589. $header .= $this->show_media_content();
  1590. }
  1591. $header .= Display::page_subheader2($counter_label . ". " . $question_title);
  1592. $header .= Display::div(
  1593. "<div class=\"rib rib-$class\"><h3>$score_label</h3></div> <h4>{$score['result']}</h4>",
  1594. array('class' => 'ribbon')
  1595. );
  1596. $header .= Display::div($this->description, array('id' => 'question_description'));
  1597. return $header;
  1598. }
  1599. /**
  1600. * Create a question from a set of parameters
  1601. * @param int Quiz ID
  1602. * @param string Question name
  1603. * @param int Maximum result for the question
  1604. * @param int Type of question (see constants at beginning of question.class.php)
  1605. * @param int Question level/category
  1606. * @param string $quiz_id
  1607. */
  1608. public function create_question(
  1609. $quiz_id,
  1610. $question_name,
  1611. $question_description = "" ,
  1612. $max_score = 0,
  1613. $type = 1,
  1614. $level = 1
  1615. ) {
  1616. $course_id = api_get_course_int_id();
  1617. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1618. $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1619. $quiz_id = intval($quiz_id);
  1620. $max_score = (float) $max_score;
  1621. $type = intval($type);
  1622. $level = intval($level);
  1623. // Get the max position
  1624. $sql = "SELECT max(position) as max_position
  1625. FROM $tbl_quiz_question q INNER JOIN $tbl_quiz_rel_question r
  1626. ON
  1627. q.id = r.question_id AND
  1628. exercice_id = $quiz_id AND
  1629. q.c_id = $course_id AND
  1630. r.c_id = $course_id";
  1631. $rs_max = Database::query($sql);
  1632. $row_max = Database::fetch_object($rs_max);
  1633. $max_position = $row_max->max_position + 1;
  1634. $params = [
  1635. 'c_id' => $course_id,
  1636. 'question' => $question_name,
  1637. 'description' => $question_description,
  1638. 'ponderation' => $max_score,
  1639. 'position' => $max_position,
  1640. 'type' => $type,
  1641. 'level' => $level,
  1642. ];
  1643. $question_id = Database::insert($tbl_quiz_question, $params);
  1644. if ($question_id) {
  1645. $sql = "UPDATE $tbl_quiz_question SET id = iid WHERE iid = $question_id";
  1646. Database::query($sql);
  1647. // Get the max question_order
  1648. $sql = "SELECT max(question_order) as max_order
  1649. FROM $tbl_quiz_rel_question
  1650. WHERE c_id = $course_id AND exercice_id = $quiz_id ";
  1651. $rs_max_order = Database::query($sql);
  1652. $row_max_order = Database::fetch_object($rs_max_order);
  1653. $max_order = $row_max_order->max_order + 1;
  1654. // Attach questions to quiz
  1655. $sql = "INSERT INTO $tbl_quiz_rel_question (c_id, question_id, exercice_id, question_order)
  1656. VALUES($course_id, $question_id, $quiz_id, $max_order)";
  1657. Database::query($sql);
  1658. }
  1659. return $question_id;
  1660. }
  1661. /**
  1662. * @return array the image filename of the question type
  1663. */
  1664. public function get_type_icon_html()
  1665. {
  1666. $type = $this->selectType();
  1667. $tabQuestionList = Question::get_question_type_list(); // [0]=file to include [1]=type name
  1668. require_once $tabQuestionList[$type][0];
  1669. $img = $explanation = null;
  1670. eval('$img = ' . $tabQuestionList[$type][1] . '::$typePicture;');
  1671. eval('$explanation = get_lang(' . $tabQuestionList[$type][1] . '::$explanationLangVar);');
  1672. return array($img, $explanation);
  1673. }
  1674. /**
  1675. * Get course medias
  1676. * @param int course id
  1677. * @param integer $course_id
  1678. */
  1679. static function get_course_medias(
  1680. $course_id,
  1681. $start = 0,
  1682. $limit = 100,
  1683. $sidx = "question",
  1684. $sord = "ASC",
  1685. $where_condition = array()
  1686. ) {
  1687. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1688. $default_where = array('c_id = ? AND parent_id = 0 AND type = ?' => array($course_id, MEDIA_QUESTION));
  1689. $result = Database::select(
  1690. '*',
  1691. $table_question,
  1692. array(
  1693. 'limit' => " $start, $limit",
  1694. 'where' => $default_where,
  1695. 'order' => "$sidx $sord"
  1696. )
  1697. );
  1698. return $result;
  1699. }
  1700. /**
  1701. * Get count course medias
  1702. * @param int course id
  1703. *
  1704. * @return int
  1705. */
  1706. static function get_count_course_medias($course_id)
  1707. {
  1708. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1709. $result = Database::select(
  1710. 'count(*) as count',
  1711. $table_question,
  1712. array('where' => array('c_id = ? AND parent_id = 0 AND type = ?' => array($course_id, MEDIA_QUESTION))),
  1713. 'first'
  1714. );
  1715. if ($result && isset($result['count'])) {
  1716. return $result['count'];
  1717. }
  1718. return 0;
  1719. }
  1720. /**
  1721. * @param int $course_id
  1722. * @return array
  1723. */
  1724. public static function prepare_course_media_select($course_id)
  1725. {
  1726. $medias = self::get_course_medias($course_id);
  1727. $media_list = array();
  1728. $media_list[0] = get_lang('NoMedia');
  1729. if (!empty($medias)) {
  1730. foreach($medias as $media) {
  1731. $media_list[$media['id']] = empty($media['question']) ? get_lang('Untitled') : $media['question'];
  1732. }
  1733. }
  1734. return $media_list;
  1735. }
  1736. /**
  1737. * @return integer[]
  1738. */
  1739. public static function get_default_levels()
  1740. {
  1741. $select_level = array(
  1742. 1 => 1,
  1743. 2 => 2,
  1744. 3 => 3,
  1745. 4 => 4,
  1746. 5 => 5
  1747. );
  1748. return $select_level;
  1749. }
  1750. /**
  1751. * @return null|string
  1752. */
  1753. public function show_media_content()
  1754. {
  1755. $html = null;
  1756. if ($this->parent_id != 0) {
  1757. $parent_question = Question::read($this->parent_id);
  1758. $html = $parent_question->show_media_content();
  1759. } else {
  1760. $html .= Display::page_subheader($this->selectTitle());
  1761. $html .= $this->selectDescription();
  1762. }
  1763. return $html;
  1764. }
  1765. /**
  1766. * Swap between unique and multiple type answers
  1767. * @return object
  1768. */
  1769. public function swapSimpleAnswerTypes()
  1770. {
  1771. $oppositeAnswers = array(
  1772. UNIQUE_ANSWER => MULTIPLE_ANSWER,
  1773. MULTIPLE_ANSWER => UNIQUE_ANSWER
  1774. );
  1775. $this->type = $oppositeAnswers[$this->type];
  1776. Database::update(
  1777. Database::get_course_table(TABLE_QUIZ_QUESTION),
  1778. array('type' => $this->type),
  1779. array('c_id = ? AND id = ?' => array($this->course['real_id'], $this->id))
  1780. );
  1781. $answerClasses = array(
  1782. UNIQUE_ANSWER => 'UniqueAnswer',
  1783. MULTIPLE_ANSWER => 'MultipleAnswer'
  1784. );
  1785. $swappedAnswer = new $answerClasses[$this->type];
  1786. foreach ($this as $key => $value) {
  1787. $swappedAnswer->$key = $value;
  1788. }
  1789. return $swappedAnswer;
  1790. }
  1791. }