question.class.php 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CQuizAnswer;
  4. /**
  5. * Class Question.
  6. *
  7. * This class allows to instantiate an object of type Question
  8. *
  9. * @author Olivier Brouckaert, original author
  10. * @author Patrick Cool, LaTeX support
  11. * @author Julio Montoya <gugli100@gmail.com> lot of bug fixes
  12. * @author hubert.borderiou@grenet.fr - add question categories
  13. *
  14. * @package chamilo.exercise
  15. */
  16. abstract class Question
  17. {
  18. public $id;
  19. public $iid;
  20. public $question;
  21. public $description;
  22. public $weighting;
  23. public $position;
  24. public $type;
  25. public $level;
  26. public $picture;
  27. public $exerciseList; // array with the list of exercises which this question is in
  28. public $category_list;
  29. public $parent_id;
  30. public $category;
  31. public $isContent;
  32. public $course;
  33. public $feedback;
  34. public static $typePicture = 'new_question.png';
  35. public static $explanationLangVar = '';
  36. public $question_table_class = 'table table-striped';
  37. public $questionTypeWithFeedback;
  38. public $extra;
  39. public $export = false;
  40. public $code;
  41. public static $questionTypes = [
  42. UNIQUE_ANSWER => ['unique_answer.class.php', 'UniqueAnswer'],
  43. MULTIPLE_ANSWER => ['multiple_answer.class.php', 'MultipleAnswer'],
  44. FILL_IN_BLANKS => ['fill_blanks.class.php', 'FillBlanks'],
  45. MATCHING => ['matching.class.php', 'Matching'],
  46. FREE_ANSWER => ['freeanswer.class.php', 'FreeAnswer'],
  47. ORAL_EXPRESSION => ['oral_expression.class.php', 'OralExpression'],
  48. HOT_SPOT => ['hotspot.class.php', 'HotSpot'],
  49. HOT_SPOT_DELINEATION => ['hotspot.class.php', 'HotspotDelineation'],
  50. MULTIPLE_ANSWER_COMBINATION => ['multiple_answer_combination.class.php', 'MultipleAnswerCombination'],
  51. UNIQUE_ANSWER_NO_OPTION => ['unique_answer_no_option.class.php', 'UniqueAnswerNoOption'],
  52. MULTIPLE_ANSWER_TRUE_FALSE => ['multiple_answer_true_false.class.php', 'MultipleAnswerTrueFalse'],
  53. MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY => [
  54. 'MultipleAnswerTrueFalseDegreeCertainty.php',
  55. 'MultipleAnswerTrueFalseDegreeCertainty',
  56. ],
  57. MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE => [
  58. 'multiple_answer_combination_true_false.class.php',
  59. 'MultipleAnswerCombinationTrueFalse',
  60. ],
  61. GLOBAL_MULTIPLE_ANSWER => ['global_multiple_answer.class.php', 'GlobalMultipleAnswer'],
  62. CALCULATED_ANSWER => ['calculated_answer.class.php', 'CalculatedAnswer'],
  63. UNIQUE_ANSWER_IMAGE => ['UniqueAnswerImage.php', 'UniqueAnswerImage'],
  64. DRAGGABLE => ['Draggable.php', 'Draggable'],
  65. MATCHING_DRAGGABLE => ['MatchingDraggable.php', 'MatchingDraggable'],
  66. //MEDIA_QUESTION => array('media_question.class.php' , 'MediaQuestion')
  67. ANNOTATION => ['Annotation.php', 'Annotation'],
  68. READING_COMPREHENSION => ['ReadingComprehension.php', 'ReadingComprehension'],
  69. ];
  70. /**
  71. * constructor of the class.
  72. *
  73. * @author Olivier Brouckaert
  74. */
  75. public function __construct()
  76. {
  77. $this->id = 0;
  78. $this->iid = 0;
  79. $this->question = '';
  80. $this->description = '';
  81. $this->weighting = 0;
  82. $this->position = 1;
  83. $this->picture = '';
  84. $this->level = 1;
  85. $this->category = 0;
  86. // This variable is used when loading an exercise like an scenario with
  87. // an special hotspot: final_overlap, final_missing, final_excess
  88. $this->extra = '';
  89. $this->exerciseList = [];
  90. $this->course = api_get_course_info();
  91. $this->category_list = [];
  92. $this->parent_id = 0;
  93. // See BT#12611
  94. $this->questionTypeWithFeedback = [
  95. MATCHING,
  96. MATCHING_DRAGGABLE,
  97. DRAGGABLE,
  98. FILL_IN_BLANKS,
  99. FREE_ANSWER,
  100. ORAL_EXPRESSION,
  101. CALCULATED_ANSWER,
  102. ANNOTATION,
  103. ];
  104. }
  105. /**
  106. * @return int|null
  107. */
  108. public function getIsContent()
  109. {
  110. $isContent = null;
  111. if (isset($_REQUEST['isContent'])) {
  112. $isContent = intval($_REQUEST['isContent']);
  113. }
  114. return $this->isContent = $isContent;
  115. }
  116. /**
  117. * Reads question information from the data base.
  118. *
  119. * @param int $id - question ID
  120. * @param array $course_info
  121. * @param bool $getExerciseList
  122. *
  123. * @return Question
  124. *
  125. * @author Olivier Brouckaert
  126. */
  127. public static function read($id, $course_info = [], $getExerciseList = true)
  128. {
  129. $id = (int) $id;
  130. if (empty($course_info)) {
  131. $course_info = api_get_course_info();
  132. }
  133. $course_id = $course_info['real_id'];
  134. if (empty($course_id) || $course_id == -1) {
  135. return false;
  136. }
  137. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  138. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  139. $sql = "SELECT *
  140. FROM $TBL_QUESTIONS
  141. WHERE c_id = $course_id AND id = $id ";
  142. $result = Database::query($sql);
  143. // if the question has been found
  144. if ($object = Database::fetch_object($result)) {
  145. $objQuestion = self::getInstance($object->type);
  146. if (!empty($objQuestion)) {
  147. $objQuestion->id = (int) $id;
  148. $objQuestion->iid = (int) $object->iid;
  149. $objQuestion->question = $object->question;
  150. $objQuestion->description = $object->description;
  151. $objQuestion->weighting = $object->ponderation;
  152. $objQuestion->position = $object->position;
  153. $objQuestion->type = (int) $object->type;
  154. $objQuestion->picture = $object->picture;
  155. $objQuestion->level = (int) $object->level;
  156. $objQuestion->extra = $object->extra;
  157. $objQuestion->course = $course_info;
  158. $objQuestion->feedback = isset($object->feedback) ? $object->feedback : '';
  159. $objQuestion->category = TestCategory::getCategoryForQuestion($id, $course_id);
  160. $objQuestion->code = isset($object->code) ? $object->code : '';
  161. if ($getExerciseList) {
  162. $tblQuiz = Database::get_course_table(TABLE_QUIZ_TEST);
  163. $sql = "SELECT DISTINCT q.exercice_id
  164. FROM $TBL_EXERCISE_QUESTION q
  165. INNER JOIN $tblQuiz e
  166. ON e.c_id = q.c_id AND e.id = q.exercice_id
  167. WHERE
  168. q.c_id = $course_id AND
  169. q.question_id = $id AND
  170. e.active >= 0";
  171. $result = Database::query($sql);
  172. // fills the array with the exercises which this question is in
  173. if ($result) {
  174. while ($obj = Database::fetch_object($result)) {
  175. $objQuestion->exerciseList[] = $obj->exercice_id;
  176. }
  177. }
  178. }
  179. return $objQuestion;
  180. }
  181. }
  182. // question not found
  183. return false;
  184. }
  185. /**
  186. * returns the question ID.
  187. *
  188. * @author Olivier Brouckaert
  189. *
  190. * @return int - question ID
  191. */
  192. public function selectId()
  193. {
  194. return $this->id;
  195. }
  196. /**
  197. * returns the question title.
  198. *
  199. * @author Olivier Brouckaert
  200. *
  201. * @return string - question title
  202. */
  203. public function selectTitle()
  204. {
  205. if (!api_get_configuration_value('save_titles_as_html')) {
  206. return $this->question;
  207. }
  208. return Display::div($this->question, ['style' => 'display: inline-block;']);
  209. }
  210. /**
  211. * @param int $itemNumber
  212. *
  213. * @return string
  214. */
  215. public function getTitleToDisplay($itemNumber)
  216. {
  217. $showQuestionTitleHtml = api_get_configuration_value('save_titles_as_html');
  218. $title = '';
  219. if (api_get_configuration_value('show_question_id')) {
  220. $title .= '<h4>#'.$this->course['code'].'-'.$this->iid.'</h4>';
  221. }
  222. $title .= $showQuestionTitleHtml ? '' : '<strong>';
  223. $title .= $itemNumber.'. '.$this->selectTitle();
  224. $title .= $showQuestionTitleHtml ? '' : '</strong>';
  225. return Display::div(
  226. $title,
  227. ['class' => 'question_title']
  228. );
  229. }
  230. /**
  231. * returns the question description.
  232. *
  233. * @author Olivier Brouckaert
  234. *
  235. * @return string - question description
  236. */
  237. public function selectDescription()
  238. {
  239. return $this->description;
  240. }
  241. /**
  242. * returns the question weighting.
  243. *
  244. * @author Olivier Brouckaert
  245. *
  246. * @return int - question weighting
  247. */
  248. public function selectWeighting()
  249. {
  250. return $this->weighting;
  251. }
  252. /**
  253. * returns the question position.
  254. *
  255. * @author Olivier Brouckaert
  256. *
  257. * @return int - question position
  258. */
  259. public function selectPosition()
  260. {
  261. return $this->position;
  262. }
  263. /**
  264. * returns the answer type.
  265. *
  266. * @author Olivier Brouckaert
  267. *
  268. * @return int - answer type
  269. */
  270. public function selectType()
  271. {
  272. return $this->type;
  273. }
  274. /**
  275. * returns the level of the question.
  276. *
  277. * @author Nicolas Raynaud
  278. *
  279. * @return int - level of the question, 0 by default
  280. */
  281. public function getLevel()
  282. {
  283. return $this->level;
  284. }
  285. /**
  286. * returns the picture name.
  287. *
  288. * @author Olivier Brouckaert
  289. *
  290. * @return string - picture name
  291. */
  292. public function selectPicture()
  293. {
  294. return $this->picture;
  295. }
  296. /**
  297. * @return string
  298. */
  299. public function selectPicturePath()
  300. {
  301. if (!empty($this->picture)) {
  302. return api_get_path(WEB_COURSE_PATH).$this->course['directory'].'/document/images/'.$this->getPictureFilename();
  303. }
  304. return '';
  305. }
  306. /**
  307. * @return int|string
  308. */
  309. public function getPictureId()
  310. {
  311. // for backward compatibility
  312. // when in field picture we had the filename not the document id
  313. if (preg_match("/quiz-.*/", $this->picture)) {
  314. return DocumentManager::get_document_id(
  315. $this->course,
  316. $this->selectPicturePath(),
  317. api_get_session_id()
  318. );
  319. }
  320. return $this->picture;
  321. }
  322. /**
  323. * @param int $courseId
  324. * @param int $sessionId
  325. *
  326. * @return string
  327. */
  328. public function getPictureFilename($courseId = 0, $sessionId = 0)
  329. {
  330. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  331. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  332. if (empty($courseId)) {
  333. return '';
  334. }
  335. // for backward compatibility
  336. // when in field picture we had the filename not the document id
  337. if (preg_match("/quiz-.*/", $this->picture)) {
  338. return $this->picture;
  339. }
  340. $pictureId = $this->getPictureId();
  341. $courseInfo = $this->course;
  342. $documentInfo = DocumentManager::get_document_data_by_id(
  343. $pictureId,
  344. $courseInfo['code'],
  345. false,
  346. $sessionId
  347. );
  348. $documentFilename = '';
  349. if ($documentInfo) {
  350. // document in document/images folder
  351. $documentFilename = pathinfo(
  352. $documentInfo['path'],
  353. PATHINFO_BASENAME
  354. );
  355. }
  356. return $documentFilename;
  357. }
  358. /**
  359. * returns the array with the exercise ID list.
  360. *
  361. * @author Olivier Brouckaert
  362. *
  363. * @return array - list of exercise ID which the question is in
  364. */
  365. public function selectExerciseList()
  366. {
  367. return $this->exerciseList;
  368. }
  369. /**
  370. * returns the number of exercises which this question is in.
  371. *
  372. * @author Olivier Brouckaert
  373. *
  374. * @return int - number of exercises
  375. */
  376. public function selectNbrExercises()
  377. {
  378. return count($this->exerciseList);
  379. }
  380. /**
  381. * changes the question title.
  382. *
  383. * @param string $title - question title
  384. *
  385. * @author Olivier Brouckaert
  386. */
  387. public function updateTitle($title)
  388. {
  389. $this->question = $title;
  390. }
  391. /**
  392. * @param int $id
  393. */
  394. public function updateParentId($id)
  395. {
  396. $this->parent_id = (int) $id;
  397. }
  398. /**
  399. * changes the question description.
  400. *
  401. * @param string $description - question description
  402. *
  403. * @author Olivier Brouckaert
  404. */
  405. public function updateDescription($description)
  406. {
  407. $this->description = $description;
  408. }
  409. /**
  410. * changes the question weighting.
  411. *
  412. * @param int $weighting - question weighting
  413. *
  414. * @author Olivier Brouckaert
  415. */
  416. public function updateWeighting($weighting)
  417. {
  418. $this->weighting = $weighting;
  419. }
  420. /**
  421. * @param array $category
  422. *
  423. * @author Hubert Borderiou 12-10-2011
  424. */
  425. public function updateCategory($category)
  426. {
  427. $this->category = $category;
  428. }
  429. /**
  430. * @param int $value
  431. *
  432. * @author Hubert Borderiou 12-10-2011
  433. */
  434. public function updateScoreAlwaysPositive($value)
  435. {
  436. $this->scoreAlwaysPositive = $value;
  437. }
  438. /**
  439. * @param int $value
  440. *
  441. * @author Hubert Borderiou 12-10-2011
  442. */
  443. public function updateUncheckedMayScore($value)
  444. {
  445. $this->uncheckedMayScore = $value;
  446. }
  447. /**
  448. * Save category of a question.
  449. *
  450. * A question can have n categories if category is empty,
  451. * then question has no category then delete the category entry
  452. *
  453. * @param array $category_list
  454. *
  455. * @author Julio Montoya - Adding multiple cat support
  456. */
  457. public function saveCategories($category_list)
  458. {
  459. if (!empty($category_list)) {
  460. $this->deleteCategory();
  461. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  462. // update or add category for a question
  463. foreach ($category_list as $category_id) {
  464. $category_id = (int) $category_id;
  465. $question_id = (int) $this->id;
  466. $sql = "SELECT count(*) AS nb
  467. FROM $table
  468. WHERE
  469. category_id = $category_id
  470. AND question_id = $question_id
  471. AND c_id=".api_get_course_int_id();
  472. $res = Database::query($sql);
  473. $row = Database::fetch_array($res);
  474. if ($row['nb'] > 0) {
  475. // DO nothing
  476. } else {
  477. $sql = "INSERT INTO $table (c_id, question_id, category_id)
  478. VALUES (".api_get_course_int_id().", $question_id, $category_id)";
  479. Database::query($sql);
  480. }
  481. }
  482. }
  483. }
  484. /**
  485. * in this version, a question can only have 1 category
  486. * if category is 0, then question has no category then delete the category entry.
  487. *
  488. * @param int $categoryId
  489. * @param int $courseId
  490. *
  491. * @return bool
  492. *
  493. * @author Hubert Borderiou 12-10-2011
  494. */
  495. public function saveCategory($categoryId, $courseId = 0)
  496. {
  497. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  498. if (empty($courseId)) {
  499. return false;
  500. }
  501. if ($categoryId <= 0) {
  502. $this->deleteCategory($courseId);
  503. } else {
  504. // update or add category for a question
  505. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  506. $categoryId = (int) $categoryId;
  507. $question_id = (int) $this->id;
  508. $sql = "SELECT count(*) AS nb FROM $table
  509. WHERE
  510. question_id = $question_id AND
  511. c_id = ".$courseId;
  512. $res = Database::query($sql);
  513. $row = Database::fetch_array($res);
  514. if ($row['nb'] > 0) {
  515. $sql = "UPDATE $table
  516. SET category_id = $categoryId
  517. WHERE
  518. question_id = $question_id AND
  519. c_id = ".$courseId;
  520. Database::query($sql);
  521. } else {
  522. $sql = "INSERT INTO $table (c_id, question_id, category_id)
  523. VALUES (".$courseId.", $question_id, $categoryId)";
  524. Database::query($sql);
  525. }
  526. return true;
  527. }
  528. }
  529. /**
  530. * @author hubert borderiou 12-10-2011
  531. *
  532. * @param int $courseId
  533. * delete any category entry for question id
  534. * delete the category for question
  535. *
  536. * @return bool
  537. */
  538. public function deleteCategory($courseId = 0)
  539. {
  540. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  541. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  542. $questionId = (int) $this->id;
  543. if (empty($courseId) || empty($questionId)) {
  544. return false;
  545. }
  546. $sql = "DELETE FROM $table
  547. WHERE
  548. question_id = $questionId AND
  549. c_id = ".$courseId;
  550. Database::query($sql);
  551. return true;
  552. }
  553. /**
  554. * changes the question position.
  555. *
  556. * @param int $position - question position
  557. *
  558. * @author Olivier Brouckaert
  559. */
  560. public function updatePosition($position)
  561. {
  562. $this->position = $position;
  563. }
  564. /**
  565. * changes the question level.
  566. *
  567. * @param int $level - question level
  568. *
  569. * @author Nicolas Raynaud
  570. */
  571. public function updateLevel($level)
  572. {
  573. $this->level = $level;
  574. }
  575. /**
  576. * changes the answer type. If the user changes the type from "unique answer" to "multiple answers"
  577. * (or conversely) answers are not deleted, otherwise yes.
  578. *
  579. * @param int $type - answer type
  580. *
  581. * @author Olivier Brouckaert
  582. */
  583. public function updateType($type)
  584. {
  585. $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
  586. $course_id = $this->course['real_id'];
  587. if (empty($course_id)) {
  588. $course_id = api_get_course_int_id();
  589. }
  590. // if we really change the type
  591. if ($type != $this->type) {
  592. // if we don't change from "unique answer" to "multiple answers" (or conversely)
  593. if (!in_array($this->type, [UNIQUE_ANSWER, MULTIPLE_ANSWER]) ||
  594. !in_array($type, [UNIQUE_ANSWER, MULTIPLE_ANSWER])
  595. ) {
  596. // removes old answers
  597. $sql = "DELETE FROM $table
  598. WHERE c_id = $course_id AND question_id = ".intval($this->id);
  599. Database::query($sql);
  600. }
  601. $this->type = $type;
  602. }
  603. }
  604. /**
  605. * Get default hot spot folder in documents.
  606. *
  607. * @param array $courseInfo
  608. *
  609. * @return string
  610. */
  611. public function getHotSpotFolderInCourse($courseInfo = [])
  612. {
  613. $courseInfo = empty($courseInfo) ? $this->course : $courseInfo;
  614. if (empty($courseInfo) || empty($courseInfo['directory'])) {
  615. // Stop everything if course is not set.
  616. api_not_allowed();
  617. }
  618. $pictureAbsolutePath = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/document/images/';
  619. $picturePath = basename($pictureAbsolutePath);
  620. if (!is_dir($picturePath)) {
  621. create_unexisting_directory(
  622. $courseInfo,
  623. api_get_user_id(),
  624. 0,
  625. 0,
  626. 0,
  627. dirname($pictureAbsolutePath),
  628. '/'.$picturePath,
  629. $picturePath,
  630. '',
  631. false,
  632. false
  633. );
  634. }
  635. return $pictureAbsolutePath;
  636. }
  637. /**
  638. * adds a picture to the question.
  639. *
  640. * @param string $picture - temporary path of the picture to upload
  641. *
  642. * @return bool - true if uploaded, otherwise false
  643. *
  644. * @author Olivier Brouckaert
  645. */
  646. public function uploadPicture($picture)
  647. {
  648. $picturePath = $this->getHotSpotFolderInCourse();
  649. // if the question has got an ID
  650. if ($this->id) {
  651. $pictureFilename = self::generatePictureName();
  652. $img = new Image($picture);
  653. $img->send_image($picturePath.'/'.$pictureFilename, -1, 'jpg');
  654. $document_id = add_document(
  655. $this->course,
  656. '/images/'.$pictureFilename,
  657. 'file',
  658. filesize($picturePath.'/'.$pictureFilename),
  659. $pictureFilename
  660. );
  661. if ($document_id) {
  662. $this->picture = $document_id;
  663. if (!file_exists($picturePath.'/'.$pictureFilename)) {
  664. return false;
  665. }
  666. api_item_property_update(
  667. $this->course,
  668. TOOL_DOCUMENT,
  669. $document_id,
  670. 'DocumentAdded',
  671. api_get_user_id()
  672. );
  673. $this->resizePicture('width', 800);
  674. return true;
  675. }
  676. }
  677. return false;
  678. }
  679. /**
  680. * return the name for image use in hotspot question
  681. * to be unique, name is quiz-[utc unix timestamp].jpg.
  682. *
  683. * @param string $prefix
  684. * @param string $extension
  685. *
  686. * @return string
  687. */
  688. public function generatePictureName($prefix = 'quiz-', $extension = 'jpg')
  689. {
  690. // image name is quiz-xxx.jpg in folder images/
  691. $utcTime = time();
  692. return $prefix.$utcTime.'.'.$extension;
  693. }
  694. /**
  695. * deletes the picture.
  696. *
  697. * @author Olivier Brouckaert
  698. *
  699. * @return bool - true if removed, otherwise false
  700. */
  701. public function removePicture()
  702. {
  703. $picturePath = $this->getHotSpotFolderInCourse();
  704. // if the question has got an ID and if the picture exists
  705. if ($this->id) {
  706. $picture = $this->picture;
  707. $this->picture = '';
  708. return @unlink($picturePath.'/'.$picture) ? true : false;
  709. }
  710. return false;
  711. }
  712. /**
  713. * Exports a picture to another question.
  714. *
  715. * @author Olivier Brouckaert
  716. *
  717. * @param int $questionId - ID of the target question
  718. * @param array $courseInfo destination course info
  719. *
  720. * @return bool - true if copied, otherwise false
  721. */
  722. public function exportPicture($questionId, $courseInfo)
  723. {
  724. if (empty($questionId) || empty($courseInfo)) {
  725. return false;
  726. }
  727. $course_id = $courseInfo['real_id'];
  728. $destination_path = $this->getHotSpotFolderInCourse($courseInfo);
  729. if (empty($destination_path)) {
  730. return false;
  731. }
  732. $source_path = $this->getHotSpotFolderInCourse();
  733. // if the question has got an ID and if the picture exists
  734. if (!$this->id || empty($this->picture)) {
  735. return false;
  736. }
  737. $sourcePictureName = $this->getPictureFilename($course_id);
  738. $picture = $this->generatePictureName();
  739. $result = false;
  740. if (file_exists($source_path.'/'.$sourcePictureName)) {
  741. // for backward compatibility
  742. $result = copy(
  743. $source_path.'/'.$sourcePictureName,
  744. $destination_path.'/'.$picture
  745. );
  746. } else {
  747. $imageInfo = DocumentManager::get_document_data_by_id(
  748. $this->picture,
  749. $courseInfo['code']
  750. );
  751. if (file_exists($imageInfo['absolute_path'])) {
  752. $result = @copy(
  753. $imageInfo['absolute_path'],
  754. $destination_path.'/'.$picture
  755. );
  756. }
  757. }
  758. // If copy was correct then add to the database
  759. if (!$result) {
  760. return false;
  761. }
  762. $table = Database::get_course_table(TABLE_QUIZ_QUESTION);
  763. $sql = "UPDATE $table SET
  764. picture = '".Database::escape_string($picture)."'
  765. WHERE c_id = $course_id AND id='".intval($questionId)."'";
  766. Database::query($sql);
  767. $documentId = add_document(
  768. $courseInfo,
  769. '/images/'.$picture,
  770. 'file',
  771. filesize($destination_path.'/'.$picture),
  772. $picture
  773. );
  774. if (!$documentId) {
  775. return false;
  776. }
  777. return api_item_property_update(
  778. $courseInfo,
  779. TOOL_DOCUMENT,
  780. $documentId,
  781. 'DocumentAdded',
  782. api_get_user_id()
  783. );
  784. }
  785. /**
  786. * Saves the picture coming from POST into a temporary file
  787. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  788. * For example, if we first show a confirmation box.
  789. *
  790. * @author Olivier Brouckaert
  791. *
  792. * @param string $picture - temporary path of the picture to move
  793. * @param string $pictureName - Name of the picture
  794. */
  795. public function setTmpPicture($picture, $pictureName)
  796. {
  797. $picturePath = $this->getHotSpotFolderInCourse();
  798. $pictureName = explode('.', $pictureName);
  799. $Extension = $pictureName[sizeof($pictureName) - 1];
  800. // saves the picture into a temporary file
  801. @move_uploaded_file($picture, $picturePath.'/tmp.'.$Extension);
  802. }
  803. /**
  804. * Set title.
  805. *
  806. * @param string $title
  807. */
  808. public function setTitle($title)
  809. {
  810. $this->question = $title;
  811. }
  812. /**
  813. * Sets extra info.
  814. *
  815. * @param string $extra
  816. */
  817. public function setExtra($extra)
  818. {
  819. $this->extra = $extra;
  820. }
  821. /**
  822. * updates the question in the data base
  823. * if an exercise ID is provided, we add that exercise ID into the exercise list.
  824. *
  825. * @author Olivier Brouckaert
  826. *
  827. * @param Exercise $exercise
  828. */
  829. public function save($exercise)
  830. {
  831. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  832. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  833. $em = Database::getManager();
  834. $exerciseId = $exercise->id;
  835. $id = $this->id;
  836. $question = $this->question;
  837. $description = $this->description;
  838. $weighting = $this->weighting;
  839. $position = $this->position;
  840. $type = $this->type;
  841. $picture = $this->picture;
  842. $level = $this->level;
  843. $extra = $this->extra;
  844. $c_id = $this->course['real_id'];
  845. $categoryId = $this->category;
  846. // question already exists
  847. if (!empty($id)) {
  848. $params = [
  849. 'question' => $question,
  850. 'description' => $description,
  851. 'ponderation' => $weighting,
  852. 'position' => $position,
  853. 'type' => $type,
  854. 'picture' => $picture,
  855. 'extra' => $extra,
  856. 'level' => $level,
  857. ];
  858. if ($exercise->questionFeedbackEnabled) {
  859. $params['feedback'] = $this->feedback;
  860. }
  861. Database::update(
  862. $TBL_QUESTIONS,
  863. $params,
  864. ['c_id = ? AND id = ?' => [$c_id, $id]]
  865. );
  866. Event::addEvent(
  867. LOG_QUESTION_UPDATED,
  868. LOG_QUESTION_ID,
  869. $this->iid
  870. );
  871. $this->saveCategory($categoryId);
  872. if (!empty($exerciseId)) {
  873. api_item_property_update(
  874. $this->course,
  875. TOOL_QUIZ,
  876. $id,
  877. 'QuizQuestionUpdated',
  878. api_get_user_id()
  879. );
  880. }
  881. if (api_get_setting('search_enabled') === 'true') {
  882. $this->search_engine_edit($exerciseId);
  883. }
  884. } else {
  885. // Creates a new question
  886. $sql = "SELECT max(position)
  887. FROM $TBL_QUESTIONS as question,
  888. $TBL_EXERCISE_QUESTION as test_question
  889. WHERE
  890. question.id = test_question.question_id AND
  891. test_question.exercice_id = ".$exerciseId." AND
  892. question.c_id = $c_id AND
  893. test_question.c_id = $c_id ";
  894. $result = Database::query($sql);
  895. $current_position = Database::result($result, 0, 0);
  896. $this->updatePosition($current_position + 1);
  897. $position = $this->position;
  898. $params = [
  899. 'c_id' => $c_id,
  900. 'question' => $question,
  901. 'description' => $description,
  902. 'ponderation' => $weighting,
  903. 'position' => $position,
  904. 'type' => $type,
  905. 'picture' => $picture,
  906. 'extra' => $extra,
  907. 'level' => $level,
  908. ];
  909. if ($exercise->questionFeedbackEnabled) {
  910. $params['feedback'] = $this->feedback;
  911. }
  912. $this->id = Database::insert($TBL_QUESTIONS, $params);
  913. if ($this->id) {
  914. $sql = "UPDATE $TBL_QUESTIONS SET id = iid WHERE iid = {$this->id}";
  915. Database::query($sql);
  916. Event::addEvent(
  917. LOG_QUESTION_CREATED,
  918. LOG_QUESTION_ID,
  919. $this->id
  920. );
  921. api_item_property_update(
  922. $this->course,
  923. TOOL_QUIZ,
  924. $this->id,
  925. 'QuizQuestionAdded',
  926. api_get_user_id()
  927. );
  928. // If hotspot, create first answer
  929. if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) {
  930. $quizAnswer = new CQuizAnswer();
  931. $quizAnswer
  932. ->setCId($c_id)
  933. ->setQuestionId($this->id)
  934. ->setAnswer('')
  935. ->setPonderation(10)
  936. ->setPosition(1)
  937. ->setHotspotCoordinates('0;0|0|0')
  938. ->setHotspotType('square');
  939. $em->persist($quizAnswer);
  940. $em->flush();
  941. $id = $quizAnswer->getIid();
  942. if ($id) {
  943. $quizAnswer
  944. ->setId($id)
  945. ->setIdAuto($id);
  946. $em->merge($quizAnswer);
  947. $em->flush();
  948. }
  949. }
  950. if ($type == HOT_SPOT_DELINEATION) {
  951. $quizAnswer = new CQuizAnswer();
  952. $quizAnswer
  953. ->setCId($c_id)
  954. ->setQuestionId($this->id)
  955. ->setAnswer('')
  956. ->setPonderation(10)
  957. ->setPosition(1)
  958. ->setHotspotCoordinates('0;0|0|0')
  959. ->setHotspotType('delineation');
  960. $em->persist($quizAnswer);
  961. $em->flush();
  962. $id = $quizAnswer->getIid();
  963. if ($id) {
  964. $quizAnswer
  965. ->setId($id)
  966. ->setIdAuto($id);
  967. $em->merge($quizAnswer);
  968. $em->flush();
  969. }
  970. }
  971. if (api_get_setting('search_enabled') === 'true') {
  972. $this->search_engine_edit($exerciseId, true);
  973. }
  974. }
  975. }
  976. // if the question is created in an exercise
  977. if (!empty($exerciseId)) {
  978. // adds the exercise into the exercise list of this question
  979. $this->addToList($exerciseId, true);
  980. }
  981. }
  982. /**
  983. * @param int $exerciseId
  984. * @param bool $addQs
  985. * @param bool $rmQs
  986. */
  987. public function search_engine_edit(
  988. $exerciseId,
  989. $addQs = false,
  990. $rmQs = false
  991. ) {
  992. // update search engine and its values table if enabled
  993. if (!empty($exerciseId) && api_get_setting('search_enabled') == 'true' &&
  994. extension_loaded('xapian')
  995. ) {
  996. $course_id = api_get_course_id();
  997. // get search_did
  998. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  999. if ($addQs || $rmQs) {
  1000. //there's only one row per question on normal db and one document per question on search engine db
  1001. $sql = 'SELECT * FROM %s
  1002. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
  1003. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1004. } else {
  1005. $sql = 'SELECT * FROM %s
  1006. WHERE course_code=\'%s\' AND tool_id=\'%s\'
  1007. AND ref_id_high_level=%s AND ref_id_second_level=%s LIMIT 1';
  1008. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  1009. }
  1010. $res = Database::query($sql);
  1011. if (Database::num_rows($res) > 0 || $addQs) {
  1012. $di = new ChamiloIndexer();
  1013. if ($addQs) {
  1014. $question_exercises = [(int) $exerciseId];
  1015. } else {
  1016. $question_exercises = [];
  1017. }
  1018. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  1019. $di->connectDb(null, null, $lang);
  1020. // retrieve others exercise ids
  1021. $se_ref = Database::fetch_array($res);
  1022. $se_doc = $di->get_document((int) $se_ref['search_did']);
  1023. if ($se_doc !== false) {
  1024. if (($se_doc_data = $di->get_document_data($se_doc)) !== false) {
  1025. $se_doc_data = UnserializeApi::unserialize(
  1026. 'not_allowed_classes',
  1027. $se_doc_data
  1028. );
  1029. if (isset($se_doc_data[SE_DATA]['type']) &&
  1030. $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION
  1031. ) {
  1032. if (isset($se_doc_data[SE_DATA]['exercise_ids']) &&
  1033. is_array($se_doc_data[SE_DATA]['exercise_ids'])
  1034. ) {
  1035. foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
  1036. if (!in_array($old_value, $question_exercises)) {
  1037. $question_exercises[] = $old_value;
  1038. }
  1039. }
  1040. }
  1041. }
  1042. }
  1043. }
  1044. if ($rmQs) {
  1045. while (($key = array_search($exerciseId, $question_exercises)) !== false) {
  1046. unset($question_exercises[$key]);
  1047. }
  1048. }
  1049. // build the chunk to index
  1050. $ic_slide = new IndexableChunk();
  1051. $ic_slide->addValue("title", $this->question);
  1052. $ic_slide->addCourseId($course_id);
  1053. $ic_slide->addToolId(TOOL_QUIZ);
  1054. $xapian_data = [
  1055. SE_COURSE_ID => $course_id,
  1056. SE_TOOL_ID => TOOL_QUIZ,
  1057. SE_DATA => [
  1058. 'type' => SE_DOCTYPE_EXERCISE_QUESTION,
  1059. 'exercise_ids' => $question_exercises,
  1060. 'question_id' => (int) $this->id,
  1061. ],
  1062. SE_USER => (int) api_get_user_id(),
  1063. ];
  1064. $ic_slide->xapian_data = serialize($xapian_data);
  1065. $ic_slide->addValue("content", $this->description);
  1066. //TODO: index answers, see also form validation on question_admin.inc.php
  1067. $di->remove_document($se_ref['search_did']);
  1068. $di->addChunk($ic_slide);
  1069. //index and return search engine document id
  1070. if (!empty($question_exercises)) { // if empty there is nothing to index
  1071. $did = $di->index();
  1072. unset($di);
  1073. }
  1074. if ($did || $rmQs) {
  1075. // save it to db
  1076. if ($addQs || $rmQs) {
  1077. $sql = "DELETE FROM %s
  1078. WHERE course_code = '%s' AND tool_id = '%s' AND ref_id_second_level = '%s'";
  1079. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1080. } else {
  1081. $sql = "DELETE FROM %S
  1082. WHERE
  1083. course_code = '%s'
  1084. AND tool_id = '%s'
  1085. AND tool_id = '%s'
  1086. AND ref_id_high_level = '%s'
  1087. AND ref_id_second_level = '%s'";
  1088. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  1089. }
  1090. Database::query($sql);
  1091. if ($rmQs) {
  1092. if (!empty($question_exercises)) {
  1093. $sql = "INSERT INTO %s (
  1094. id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
  1095. )
  1096. VALUES (
  1097. NULL, '%s', '%s', %s, %s, %s
  1098. )";
  1099. $sql = sprintf(
  1100. $sql,
  1101. $tbl_se_ref,
  1102. $course_id,
  1103. TOOL_QUIZ,
  1104. array_shift($question_exercises),
  1105. $this->id,
  1106. $did
  1107. );
  1108. Database::query($sql);
  1109. }
  1110. } else {
  1111. $sql = "INSERT INTO %s (
  1112. id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did
  1113. )
  1114. VALUES (
  1115. NULL , '%s', '%s', %s, %s, %s
  1116. )";
  1117. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
  1118. Database::query($sql);
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. /**
  1125. * adds an exercise into the exercise list.
  1126. *
  1127. * @author Olivier Brouckaert
  1128. *
  1129. * @param int $exerciseId - exercise ID
  1130. * @param bool $fromSave - from $this->save() or not
  1131. */
  1132. public function addToList($exerciseId, $fromSave = false)
  1133. {
  1134. $exerciseRelQuestionTable = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1135. $id = (int) $this->id;
  1136. $exerciseId = (int) $exerciseId;
  1137. // checks if the exercise ID is not in the list
  1138. if (!empty($exerciseId) && !in_array($exerciseId, $this->exerciseList)) {
  1139. $this->exerciseList[] = $exerciseId;
  1140. $courseId = isset($this->course['real_id']) ? $this->course['real_id'] : 0;
  1141. $newExercise = new Exercise($courseId);
  1142. $newExercise->read($exerciseId, false);
  1143. $count = $newExercise->getQuestionCount();
  1144. $count++;
  1145. $sql = "INSERT INTO $exerciseRelQuestionTable (c_id, question_id, exercice_id, question_order)
  1146. VALUES ({$this->course['real_id']}, ".$id.", ".$exerciseId.", '$count')";
  1147. Database::query($sql);
  1148. // we do not want to reindex if we had just saved adnd indexed the question
  1149. if (!$fromSave) {
  1150. $this->search_engine_edit($exerciseId, true);
  1151. }
  1152. }
  1153. }
  1154. /**
  1155. * removes an exercise from the exercise list.
  1156. *
  1157. * @author Olivier Brouckaert
  1158. *
  1159. * @param int $exerciseId - exercise ID
  1160. * @param int $courseId
  1161. *
  1162. * @return bool - true if removed, otherwise false
  1163. */
  1164. public function removeFromList($exerciseId, $courseId = 0)
  1165. {
  1166. $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1167. $id = (int) $this->id;
  1168. $exerciseId = (int) $exerciseId;
  1169. // searches the position of the exercise ID in the list
  1170. $pos = array_search($exerciseId, $this->exerciseList);
  1171. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  1172. // exercise not found
  1173. if ($pos === false) {
  1174. return false;
  1175. } else {
  1176. // deletes the position in the array containing the wanted exercise ID
  1177. unset($this->exerciseList[$pos]);
  1178. //update order of other elements
  1179. $sql = "SELECT question_order
  1180. FROM $table
  1181. WHERE
  1182. c_id = $courseId AND
  1183. question_id = $id AND
  1184. exercice_id = $exerciseId";
  1185. $res = Database::query($sql);
  1186. if (Database::num_rows($res) > 0) {
  1187. $row = Database::fetch_array($res);
  1188. if (!empty($row['question_order'])) {
  1189. $sql = "UPDATE $table
  1190. SET question_order = question_order-1
  1191. WHERE
  1192. c_id = $courseId AND
  1193. exercice_id = $exerciseId AND
  1194. question_order > ".$row['question_order'];
  1195. Database::query($sql);
  1196. }
  1197. }
  1198. $sql = "DELETE FROM $table
  1199. WHERE
  1200. c_id = $courseId AND
  1201. question_id = $id AND
  1202. exercice_id = $exerciseId";
  1203. Database::query($sql);
  1204. return true;
  1205. }
  1206. }
  1207. /**
  1208. * Deletes a question from the database
  1209. * the parameter tells if the question is removed from all exercises (value = 0),
  1210. * or just from one exercise (value = exercise ID).
  1211. *
  1212. * @author Olivier Brouckaert
  1213. *
  1214. * @param int $deleteFromEx - exercise ID if the question is only removed from one exercise
  1215. *
  1216. * @return bool
  1217. */
  1218. public function delete($deleteFromEx = 0)
  1219. {
  1220. if (empty($this->course)) {
  1221. return false;
  1222. }
  1223. $courseId = $this->course['real_id'];
  1224. if (empty($courseId)) {
  1225. return false;
  1226. }
  1227. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1228. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1229. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  1230. $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  1231. $id = (int) $this->id;
  1232. // if the question must be removed from all exercises
  1233. if (!$deleteFromEx) {
  1234. //update the question_order of each question to avoid inconsistencies
  1235. $sql = "SELECT exercice_id, question_order
  1236. FROM $TBL_EXERCISE_QUESTION
  1237. WHERE c_id = $courseId AND question_id = ".$id;
  1238. $res = Database::query($sql);
  1239. if (Database::num_rows($res) > 0) {
  1240. while ($row = Database::fetch_array($res)) {
  1241. if (!empty($row['question_order'])) {
  1242. $sql = "UPDATE $TBL_EXERCISE_QUESTION
  1243. SET question_order = question_order-1
  1244. WHERE
  1245. c_id = $courseId AND
  1246. exercice_id = ".intval($row['exercice_id'])." AND
  1247. question_order > ".$row['question_order'];
  1248. Database::query($sql);
  1249. }
  1250. }
  1251. }
  1252. $sql = "DELETE FROM $TBL_EXERCISE_QUESTION
  1253. WHERE c_id = $courseId AND question_id = ".$id;
  1254. Database::query($sql);
  1255. $sql = "DELETE FROM $TBL_QUESTIONS
  1256. WHERE c_id = $courseId AND id = ".$id;
  1257. Database::query($sql);
  1258. $sql = "DELETE FROM $TBL_REPONSES
  1259. WHERE c_id = $courseId AND question_id = ".$id;
  1260. Database::query($sql);
  1261. // remove the category of this question in the question_rel_category table
  1262. $sql = "DELETE FROM $TBL_QUIZ_QUESTION_REL_CATEGORY
  1263. WHERE
  1264. c_id = $courseId AND
  1265. question_id = ".$id;
  1266. Database::query($sql);
  1267. api_item_property_update(
  1268. $this->course,
  1269. TOOL_QUIZ,
  1270. $id,
  1271. 'QuizQuestionDeleted',
  1272. api_get_user_id()
  1273. );
  1274. $this->removePicture();
  1275. } else {
  1276. // just removes the exercise from the list
  1277. $this->removeFromList($deleteFromEx, $courseId);
  1278. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1279. // disassociate question with this exercise
  1280. $this->search_engine_edit($deleteFromEx, false, true);
  1281. }
  1282. api_item_property_update(
  1283. $this->course,
  1284. TOOL_QUIZ,
  1285. $id,
  1286. 'QuizQuestionDeleted',
  1287. api_get_user_id()
  1288. );
  1289. }
  1290. return true;
  1291. }
  1292. /**
  1293. * Duplicates the question.
  1294. *
  1295. * @author Olivier Brouckaert
  1296. *
  1297. * @param array $courseInfo Course info of the destination course
  1298. *
  1299. * @return false|string ID of the new question
  1300. */
  1301. public function duplicate($courseInfo = [])
  1302. {
  1303. $courseInfo = empty($courseInfo) ? $this->course : $courseInfo;
  1304. if (empty($courseInfo)) {
  1305. return false;
  1306. }
  1307. $questionTable = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1308. $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1309. $question = $this->question;
  1310. $description = $this->description;
  1311. $weighting = $this->weighting;
  1312. $position = $this->position;
  1313. $type = $this->type;
  1314. $level = (int) $this->level;
  1315. $extra = $this->extra;
  1316. // Using the same method used in the course copy to transform URLs
  1317. if ($this->course['id'] != $courseInfo['id']) {
  1318. $description = DocumentManager::replaceUrlWithNewCourseCode(
  1319. $description,
  1320. $this->course['code'],
  1321. $courseInfo['id']
  1322. );
  1323. $question = DocumentManager::replaceUrlWithNewCourseCode(
  1324. $question,
  1325. $this->course['code'],
  1326. $courseInfo['id']
  1327. );
  1328. }
  1329. $course_id = $courseInfo['real_id'];
  1330. // Read the source options
  1331. $options = self::readQuestionOption($this->id, $this->course['real_id']);
  1332. // Inserting in the new course db / or the same course db
  1333. $params = [
  1334. 'c_id' => $course_id,
  1335. 'question' => $question,
  1336. 'description' => $description,
  1337. 'ponderation' => $weighting,
  1338. 'position' => $position,
  1339. 'type' => $type,
  1340. 'level' => $level,
  1341. 'extra' => $extra,
  1342. ];
  1343. $newQuestionId = Database::insert($questionTable, $params);
  1344. if ($newQuestionId) {
  1345. $sql = "UPDATE $questionTable
  1346. SET id = iid
  1347. WHERE iid = $newQuestionId";
  1348. Database::query($sql);
  1349. if (!empty($options)) {
  1350. // Saving the quiz_options
  1351. foreach ($options as $item) {
  1352. $item['question_id'] = $newQuestionId;
  1353. $item['c_id'] = $course_id;
  1354. unset($item['id']);
  1355. unset($item['iid']);
  1356. $id = Database::insert($TBL_QUESTION_OPTIONS, $item);
  1357. if ($id) {
  1358. $sql = "UPDATE $TBL_QUESTION_OPTIONS
  1359. SET id = iid
  1360. WHERE iid = $id";
  1361. Database::query($sql);
  1362. }
  1363. }
  1364. }
  1365. // Duplicates the picture of the hotspot
  1366. $this->exportPicture($newQuestionId, $courseInfo);
  1367. }
  1368. return $newQuestionId;
  1369. }
  1370. /**
  1371. * @return string
  1372. */
  1373. public function get_question_type_name()
  1374. {
  1375. $key = self::$questionTypes[$this->type];
  1376. return get_lang($key[1]);
  1377. }
  1378. /**
  1379. * @param string $type
  1380. */
  1381. public static function get_question_type($type)
  1382. {
  1383. if ($type == ORAL_EXPRESSION && api_get_setting('enable_record_audio') !== 'true') {
  1384. return null;
  1385. }
  1386. return self::$questionTypes[$type];
  1387. }
  1388. /**
  1389. * @return array
  1390. */
  1391. public static function get_question_type_list()
  1392. {
  1393. if (api_get_setting('enable_record_audio') !== 'true') {
  1394. self::$questionTypes[ORAL_EXPRESSION] = null;
  1395. unset(self::$questionTypes[ORAL_EXPRESSION]);
  1396. }
  1397. if (api_get_setting('enable_quiz_scenario') !== 'true') {
  1398. self::$questionTypes[HOT_SPOT_DELINEATION] = null;
  1399. unset(self::$questionTypes[HOT_SPOT_DELINEATION]);
  1400. }
  1401. return self::$questionTypes;
  1402. }
  1403. /**
  1404. * Returns an instance of the class corresponding to the type.
  1405. *
  1406. * @param int $type the type of the question
  1407. *
  1408. * @return $this instance of a Question subclass (or of Questionc class by default)
  1409. */
  1410. public static function getInstance($type)
  1411. {
  1412. if (!is_null($type)) {
  1413. list($fileName, $className) = self::get_question_type($type);
  1414. if (!empty($fileName)) {
  1415. include_once $fileName;
  1416. if (class_exists($className)) {
  1417. return new $className();
  1418. } else {
  1419. echo 'Can\'t instanciate class '.$className.' of type '.$type;
  1420. }
  1421. }
  1422. }
  1423. return null;
  1424. }
  1425. /**
  1426. * Creates the form to create / edit a question
  1427. * A subclass can redefine this function to add fields...
  1428. *
  1429. * @param FormValidator $form
  1430. * @param Exercise $exercise
  1431. */
  1432. public function createForm(&$form, $exercise)
  1433. {
  1434. echo '<style>
  1435. .media { display:none;}
  1436. </style>';
  1437. // question name
  1438. if (api_get_configuration_value('save_titles_as_html')) {
  1439. $editorConfig = ['ToolbarSet' => 'Minimal'];
  1440. $form->addHtmlEditor(
  1441. 'questionName',
  1442. get_lang('Question'),
  1443. false,
  1444. false,
  1445. $editorConfig,
  1446. true
  1447. );
  1448. } else {
  1449. $form->addElement('text', 'questionName', get_lang('Question'));
  1450. }
  1451. $form->addRule('questionName', get_lang('GiveQuestion'), 'required');
  1452. // default content
  1453. $isContent = isset($_REQUEST['isContent']) ? (int) $_REQUEST['isContent'] : null;
  1454. // Question type
  1455. $answerType = isset($_REQUEST['answerType']) ? (int) $_REQUEST['answerType'] : null;
  1456. $form->addElement('hidden', 'answerType', $answerType);
  1457. // html editor
  1458. $editorConfig = [
  1459. 'ToolbarSet' => 'TestQuestionDescription',
  1460. 'Height' => '150',
  1461. ];
  1462. if (!api_is_allowed_to_edit(null, true)) {
  1463. $editorConfig['UserStatus'] = 'student';
  1464. }
  1465. $form->addButtonAdvancedSettings('advanced_params');
  1466. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  1467. $form->addHtmlEditor(
  1468. 'questionDescription',
  1469. get_lang('QuestionDescription'),
  1470. false,
  1471. false,
  1472. $editorConfig
  1473. );
  1474. if ($this->type != MEDIA_QUESTION) {
  1475. // Advanced parameters
  1476. $select_level = self::get_default_levels();
  1477. $form->addElement(
  1478. 'select',
  1479. 'questionLevel',
  1480. get_lang('Difficulty'),
  1481. $select_level
  1482. );
  1483. // Categories
  1484. $tabCat = TestCategory::getCategoriesIdAndName();
  1485. $form->addElement(
  1486. 'select',
  1487. 'questionCategory',
  1488. get_lang('Category'),
  1489. $tabCat
  1490. );
  1491. global $text;
  1492. switch ($this->type) {
  1493. case UNIQUE_ANSWER:
  1494. $buttonGroup = [];
  1495. $buttonGroup[] = $form->addButtonSave(
  1496. $text,
  1497. 'submitQuestion',
  1498. true
  1499. );
  1500. $buttonGroup[] = $form->addButton(
  1501. 'convertAnswer',
  1502. get_lang('ConvertToMultipleAnswer'),
  1503. 'dot-circle-o',
  1504. 'default',
  1505. null,
  1506. null,
  1507. null,
  1508. true
  1509. );
  1510. $form->addGroup($buttonGroup);
  1511. break;
  1512. case MULTIPLE_ANSWER:
  1513. $buttonGroup = [];
  1514. $buttonGroup[] = $form->addButtonSave(
  1515. $text,
  1516. 'submitQuestion',
  1517. true
  1518. );
  1519. $buttonGroup[] = $form->addButton(
  1520. 'convertAnswer',
  1521. get_lang('ConvertToUniqueAnswer'),
  1522. 'check-square-o',
  1523. 'default',
  1524. null,
  1525. null,
  1526. null,
  1527. true
  1528. );
  1529. $form->addGroup($buttonGroup);
  1530. break;
  1531. }
  1532. //Medias
  1533. //$course_medias = self::prepare_course_media_select(api_get_course_int_id());
  1534. //$form->addElement('select', 'parent_id', get_lang('AttachToMedia'), $course_medias);
  1535. }
  1536. $form->addElement('html', '</div>');
  1537. if (!isset($_GET['fromExercise'])) {
  1538. switch ($answerType) {
  1539. case 1:
  1540. $this->question = get_lang('DefaultUniqueQuestion');
  1541. break;
  1542. case 2:
  1543. $this->question = get_lang('DefaultMultipleQuestion');
  1544. break;
  1545. case 3:
  1546. $this->question = get_lang('DefaultFillBlankQuestion');
  1547. break;
  1548. case 4:
  1549. $this->question = get_lang('DefaultMathingQuestion');
  1550. break;
  1551. case 5:
  1552. $this->question = get_lang('DefaultOpenQuestion');
  1553. break;
  1554. case 9:
  1555. $this->question = get_lang('DefaultMultipleQuestion');
  1556. break;
  1557. }
  1558. }
  1559. if (!is_null($exercise)) {
  1560. if ($exercise->questionFeedbackEnabled && $this->showFeedback($exercise)) {
  1561. $form->addTextarea('feedback', get_lang('FeedbackIfNotCorrect'));
  1562. }
  1563. }
  1564. // default values
  1565. $defaults = [];
  1566. $defaults['questionName'] = $this->question;
  1567. $defaults['questionDescription'] = $this->description;
  1568. $defaults['questionLevel'] = $this->level;
  1569. $defaults['questionCategory'] = $this->category;
  1570. $defaults['feedback'] = $this->feedback;
  1571. // Came from he question pool
  1572. if (isset($_GET['fromExercise'])) {
  1573. $form->setDefaults($defaults);
  1574. }
  1575. if (!isset($_GET['newQuestion']) || $isContent) {
  1576. $form->setDefaults($defaults);
  1577. }
  1578. /*if (!empty($_REQUEST['myid'])) {
  1579. $form->setDefaults($defaults);
  1580. } else {
  1581. if ($isContent == 1) {
  1582. $form->setDefaults($defaults);
  1583. }
  1584. }*/
  1585. }
  1586. /**
  1587. * function which process the creation of questions.
  1588. *
  1589. * @param FormValidator $form
  1590. * @param Exercise $exercise
  1591. */
  1592. public function processCreation($form, $exercise)
  1593. {
  1594. $this->updateTitle($form->getSubmitValue('questionName'));
  1595. $this->updateDescription($form->getSubmitValue('questionDescription'));
  1596. $this->updateLevel($form->getSubmitValue('questionLevel'));
  1597. $this->updateCategory($form->getSubmitValue('questionCategory'));
  1598. $this->setFeedback($form->getSubmitValue('feedback'));
  1599. //Save normal question if NOT media
  1600. if ($this->type != MEDIA_QUESTION) {
  1601. $this->save($exercise);
  1602. // modify the exercise
  1603. $exercise->addToList($this->id);
  1604. $exercise->update_question_positions();
  1605. }
  1606. }
  1607. /**
  1608. * abstract function which creates the form to create / edit the answers of the question.
  1609. *
  1610. * @param FormValidator $form
  1611. */
  1612. abstract public function createAnswersForm($form);
  1613. /**
  1614. * abstract function which process the creation of answers.
  1615. *
  1616. * @param FormValidator $form
  1617. * @param Exercise $exercise
  1618. */
  1619. abstract public function processAnswersCreation($form, $exercise);
  1620. /**
  1621. * Displays the menu of question types.
  1622. *
  1623. * @param Exercise $objExercise
  1624. */
  1625. public static function displayTypeMenu($objExercise)
  1626. {
  1627. $feedbackType = $objExercise->getFeedbackType();
  1628. $exerciseId = $objExercise->id;
  1629. // 1. by default we show all the question types
  1630. $question_type_custom_list = self::get_question_type_list();
  1631. if (!isset($feedbackType)) {
  1632. $feedbackType = 0;
  1633. }
  1634. if (in_array($feedbackType, [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  1635. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  1636. $question_type_custom_list = [
  1637. UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],
  1638. HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION],
  1639. ];
  1640. } else {
  1641. unset($question_type_custom_list[HOT_SPOT_DELINEATION]);
  1642. }
  1643. echo '<div class="panel panel-default">';
  1644. echo '<div class="panel-body">';
  1645. echo '<ul class="question_menu">';
  1646. foreach ($question_type_custom_list as $i => $a_type) {
  1647. // @todo remove require_once classes are already loaded using composer
  1648. // include the class of the type
  1649. require_once $a_type[0];
  1650. // get the picture of the type and the langvar which describes it
  1651. $img = $explanation = '';
  1652. eval('$img = '.$a_type[1].'::$typePicture;');
  1653. eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
  1654. echo '<li>';
  1655. echo '<div class="icon-image">';
  1656. $icon = '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.
  1657. Display::return_icon($img, $explanation, null, ICON_SIZE_BIG).'</a>';
  1658. if ($objExercise->force_edit_exercise_in_lp === false) {
  1659. if ($objExercise->exercise_was_added_in_lp == true) {
  1660. $img = pathinfo($img);
  1661. $img = $img['filename'].'_na.'.$img['extension'];
  1662. $icon = Display::return_icon($img, $explanation, null, ICON_SIZE_BIG);
  1663. }
  1664. }
  1665. echo $icon;
  1666. echo '</div>';
  1667. echo '</li>';
  1668. }
  1669. echo '<li>';
  1670. echo '<div class="icon_image_content">';
  1671. if ($objExercise->exercise_was_added_in_lp == true) {
  1672. echo Display::return_icon(
  1673. 'database_na.png',
  1674. get_lang('GetExistingQuestion'),
  1675. null,
  1676. ICON_SIZE_BIG
  1677. );
  1678. } else {
  1679. if (in_array($feedbackType, [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  1680. echo $url = "<a href=\"question_pool.php?".api_get_cidreq()."&type=1&fromExercise=$exerciseId\">";
  1681. } else {
  1682. echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&fromExercise='.$exerciseId.'">';
  1683. }
  1684. echo Display::return_icon(
  1685. 'database.png',
  1686. get_lang('GetExistingQuestion'),
  1687. null,
  1688. ICON_SIZE_BIG
  1689. );
  1690. }
  1691. echo '</a>';
  1692. echo '</div></li>';
  1693. echo '</ul>';
  1694. echo '</div>';
  1695. echo '</div>';
  1696. }
  1697. /**
  1698. * @param int $question_id
  1699. * @param string $name
  1700. * @param int $course_id
  1701. * @param int $position
  1702. *
  1703. * @return false|string
  1704. */
  1705. public static function saveQuestionOption($question_id, $name, $course_id, $position = 0)
  1706. {
  1707. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1708. $params['question_id'] = (int) $question_id;
  1709. $params['name'] = $name;
  1710. $params['position'] = $position;
  1711. $params['c_id'] = $course_id;
  1712. $result = self::readQuestionOption($question_id, $course_id);
  1713. $last_id = Database::insert($table, $params);
  1714. if ($last_id) {
  1715. $sql = "UPDATE $table SET id = iid WHERE iid = $last_id";
  1716. Database::query($sql);
  1717. }
  1718. return $last_id;
  1719. }
  1720. /**
  1721. * @param int $question_id
  1722. * @param int $course_id
  1723. */
  1724. public static function deleteAllQuestionOptions($question_id, $course_id)
  1725. {
  1726. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1727. Database::delete(
  1728. $table,
  1729. [
  1730. 'c_id = ? AND question_id = ?' => [
  1731. $course_id,
  1732. $question_id,
  1733. ],
  1734. ]
  1735. );
  1736. }
  1737. /**
  1738. * @param int $id
  1739. * @param array $params
  1740. * @param int $course_id
  1741. *
  1742. * @return bool|int
  1743. */
  1744. public static function updateQuestionOption($id, $params, $course_id)
  1745. {
  1746. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1747. $result = Database::update(
  1748. $table,
  1749. $params,
  1750. ['c_id = ? AND id = ?' => [$course_id, $id]]
  1751. );
  1752. return $result;
  1753. }
  1754. /**
  1755. * @param int $question_id
  1756. * @param int $course_id
  1757. *
  1758. * @return array
  1759. */
  1760. public static function readQuestionOption($question_id, $course_id)
  1761. {
  1762. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1763. $result = Database::select(
  1764. '*',
  1765. $table,
  1766. [
  1767. 'where' => [
  1768. 'c_id = ? AND question_id = ?' => [
  1769. $course_id,
  1770. $question_id,
  1771. ],
  1772. ],
  1773. 'order' => 'id ASC',
  1774. ]
  1775. );
  1776. return $result;
  1777. }
  1778. /**
  1779. * Shows question title an description.
  1780. *
  1781. * @param Exercise $exercise
  1782. * @param int $counter
  1783. * @param array $score
  1784. *
  1785. * @return string HTML string with the header of the question (before the answers table)
  1786. */
  1787. public function return_header(Exercise $exercise, $counter = null, $score = [])
  1788. {
  1789. $counterLabel = '';
  1790. if (!empty($counter)) {
  1791. $counterLabel = (int) $counter;
  1792. }
  1793. $scoreLabel = get_lang('Wrong');
  1794. if (in_array($exercise->results_disabled, [
  1795. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  1796. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  1797. ])
  1798. ) {
  1799. $scoreLabel = get_lang('QuizWrongAnswerHereIsTheCorrectOne');
  1800. }
  1801. $class = 'error';
  1802. if (isset($score['pass']) && $score['pass'] == true) {
  1803. $scoreLabel = get_lang('Correct');
  1804. if (in_array($exercise->results_disabled, [
  1805. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  1806. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  1807. ])
  1808. ) {
  1809. $scoreLabel = get_lang('CorrectAnswer');
  1810. }
  1811. $class = 'success';
  1812. }
  1813. switch ($this->type) {
  1814. case FREE_ANSWER:
  1815. case ORAL_EXPRESSION:
  1816. case ANNOTATION:
  1817. $score['revised'] = isset($score['revised']) ? $score['revised'] : false;
  1818. if ($score['revised'] == true) {
  1819. $scoreLabel = get_lang('Revised');
  1820. $class = '';
  1821. } else {
  1822. $scoreLabel = get_lang('NotRevised');
  1823. $class = 'warning';
  1824. if (isset($score['weight'])) {
  1825. $weight = float_format($score['weight'], 1);
  1826. $score['result'] = ' ? / '.$weight;
  1827. }
  1828. $model = ExerciseLib::getCourseScoreModel();
  1829. if (!empty($model)) {
  1830. $score['result'] = ' ? ';
  1831. }
  1832. $hide = api_get_configuration_value('hide_free_question_score');
  1833. if ($hide === true) {
  1834. $score['result'] = '-';
  1835. }
  1836. }
  1837. break;
  1838. case UNIQUE_ANSWER:
  1839. if (in_array($exercise->results_disabled, [
  1840. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  1841. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  1842. ])
  1843. ) {
  1844. if (isset($score['user_answered'])) {
  1845. if ($score['user_answered'] === false) {
  1846. $scoreLabel = get_lang('Unanswered');
  1847. $class = 'info';
  1848. }
  1849. }
  1850. }
  1851. break;
  1852. }
  1853. // display question category, if any
  1854. $header = '';
  1855. if ($exercise->display_category_name) {
  1856. $header = TestCategory::returnCategoryAndTitle($this->id);
  1857. }
  1858. $show_media = '';
  1859. if ($show_media) {
  1860. $header .= $this->show_media_content();
  1861. }
  1862. $scoreCurrent = [
  1863. 'used' => isset($score['score']) ? $score['score'] : '',
  1864. 'missing' => isset($score['weight']) ? $score['weight'] : '',
  1865. ];
  1866. $header .= Display::page_subheader2($counterLabel.'. '.$this->question);
  1867. // dont display score for certainty degree questions
  1868. if ($this->type != MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  1869. if (isset($score['result'])) {
  1870. if (in_array($exercise->results_disabled, [
  1871. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  1872. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  1873. ])
  1874. ) {
  1875. $score['result'] = null;
  1876. }
  1877. $header .= $exercise->getQuestionRibbon($class, $scoreLabel, $score['result'], $scoreCurrent);
  1878. }
  1879. }
  1880. if ($this->type != READING_COMPREHENSION) {
  1881. // Do not show the description (the text to read) if the question is of type READING_COMPREHENSION
  1882. $header .= Display::div(
  1883. $this->description,
  1884. ['class' => 'question_description']
  1885. );
  1886. } else {
  1887. if ($score['pass'] == true) {
  1888. $message = Display::div(
  1889. sprintf(
  1890. get_lang('ReadingQuestionCongratsSpeedXReachedForYWords'),
  1891. ReadingComprehension::$speeds[$this->level],
  1892. $this->getWordsCount()
  1893. )
  1894. );
  1895. } else {
  1896. $message = Display::div(
  1897. sprintf(
  1898. get_lang('ReadingQuestionCongratsSpeedXNotReachedForYWords'),
  1899. ReadingComprehension::$speeds[$this->level],
  1900. $this->getWordsCount()
  1901. )
  1902. );
  1903. }
  1904. $header .= $message.'<br />';
  1905. }
  1906. if (isset($score['pass']) && $score['pass'] === false) {
  1907. if ($this->showFeedback($exercise)) {
  1908. $header .= $this->returnFormatFeedback();
  1909. }
  1910. }
  1911. return $header;
  1912. }
  1913. /**
  1914. * @deprecated
  1915. * Create a question from a set of parameters.
  1916. *
  1917. * @param int Quiz ID
  1918. * @param string Question name
  1919. * @param int Maximum result for the question
  1920. * @param int Type of question (see constants at beginning of question.class.php)
  1921. * @param int Question level/category
  1922. * @param string $quiz_id
  1923. */
  1924. public function create_question(
  1925. $quiz_id,
  1926. $question_name,
  1927. $question_description = '',
  1928. $max_score = 0,
  1929. $type = 1,
  1930. $level = 1
  1931. ) {
  1932. $course_id = api_get_course_int_id();
  1933. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1934. $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1935. $quiz_id = intval($quiz_id);
  1936. $max_score = (float) $max_score;
  1937. $type = intval($type);
  1938. $level = intval($level);
  1939. // Get the max position
  1940. $sql = "SELECT max(position) as max_position
  1941. FROM $tbl_quiz_question q
  1942. INNER JOIN $tbl_quiz_rel_question r
  1943. ON
  1944. q.id = r.question_id AND
  1945. exercice_id = $quiz_id AND
  1946. q.c_id = $course_id AND
  1947. r.c_id = $course_id";
  1948. $rs_max = Database::query($sql);
  1949. $row_max = Database::fetch_object($rs_max);
  1950. $max_position = $row_max->max_position + 1;
  1951. $params = [
  1952. 'c_id' => $course_id,
  1953. 'question' => $question_name,
  1954. 'description' => $question_description,
  1955. 'ponderation' => $max_score,
  1956. 'position' => $max_position,
  1957. 'type' => $type,
  1958. 'level' => $level,
  1959. ];
  1960. $question_id = Database::insert($tbl_quiz_question, $params);
  1961. if ($question_id) {
  1962. $sql = "UPDATE $tbl_quiz_question
  1963. SET id = iid WHERE iid = $question_id";
  1964. Database::query($sql);
  1965. // Get the max question_order
  1966. $sql = "SELECT max(question_order) as max_order
  1967. FROM $tbl_quiz_rel_question
  1968. WHERE c_id = $course_id AND exercice_id = $quiz_id ";
  1969. $rs_max_order = Database::query($sql);
  1970. $row_max_order = Database::fetch_object($rs_max_order);
  1971. $max_order = $row_max_order->max_order + 1;
  1972. // Attach questions to quiz
  1973. $sql = "INSERT INTO $tbl_quiz_rel_question (c_id, question_id, exercice_id, question_order)
  1974. VALUES($course_id, $question_id, $quiz_id, $max_order)";
  1975. Database::query($sql);
  1976. }
  1977. return $question_id;
  1978. }
  1979. /**
  1980. * @return array the image filename of the question type
  1981. */
  1982. public function get_type_icon_html()
  1983. {
  1984. $type = $this->selectType();
  1985. $tabQuestionList = self::get_question_type_list(); // [0]=file to include [1]=type name
  1986. require_once $tabQuestionList[$type][0];
  1987. $img = $explanation = null;
  1988. eval('$img = '.$tabQuestionList[$type][1].'::$typePicture;');
  1989. eval('$explanation = get_lang('.$tabQuestionList[$type][1].'::$explanationLangVar);');
  1990. return [$img, $explanation];
  1991. }
  1992. /**
  1993. * Get course medias.
  1994. *
  1995. * @param int course id
  1996. * @param int $course_id
  1997. *
  1998. * @return array
  1999. */
  2000. public static function get_course_medias(
  2001. $course_id,
  2002. $start = 0,
  2003. $limit = 100,
  2004. $sidx = "question",
  2005. $sord = "ASC",
  2006. $where_condition = []
  2007. ) {
  2008. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2009. $default_where = [
  2010. 'c_id = ? AND parent_id = 0 AND type = ?' => [
  2011. $course_id,
  2012. MEDIA_QUESTION,
  2013. ],
  2014. ];
  2015. $result = Database::select(
  2016. '*',
  2017. $table_question,
  2018. [
  2019. 'limit' => " $start, $limit",
  2020. 'where' => $default_where,
  2021. 'order' => "$sidx $sord",
  2022. ]
  2023. );
  2024. return $result;
  2025. }
  2026. /**
  2027. * Get count course medias.
  2028. *
  2029. * @param int course id
  2030. *
  2031. * @return int
  2032. */
  2033. public static function get_count_course_medias($course_id)
  2034. {
  2035. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2036. $result = Database::select(
  2037. 'count(*) as count',
  2038. $table_question,
  2039. [
  2040. 'where' => [
  2041. 'c_id = ? AND parent_id = 0 AND type = ?' => [
  2042. $course_id,
  2043. MEDIA_QUESTION,
  2044. ],
  2045. ],
  2046. ],
  2047. 'first'
  2048. );
  2049. if ($result && isset($result['count'])) {
  2050. return $result['count'];
  2051. }
  2052. return 0;
  2053. }
  2054. /**
  2055. * @param int $course_id
  2056. *
  2057. * @return array
  2058. */
  2059. public static function prepare_course_media_select($course_id)
  2060. {
  2061. $medias = self::get_course_medias($course_id);
  2062. $media_list = [];
  2063. $media_list[0] = get_lang('NoMedia');
  2064. if (!empty($medias)) {
  2065. foreach ($medias as $media) {
  2066. $media_list[$media['id']] = empty($media['question']) ? get_lang('Untitled') : $media['question'];
  2067. }
  2068. }
  2069. return $media_list;
  2070. }
  2071. /**
  2072. * @return array
  2073. */
  2074. public static function get_default_levels()
  2075. {
  2076. $levels = [
  2077. 1 => 1,
  2078. 2 => 2,
  2079. 3 => 3,
  2080. 4 => 4,
  2081. 5 => 5,
  2082. ];
  2083. return $levels;
  2084. }
  2085. /**
  2086. * @return string
  2087. */
  2088. public function show_media_content()
  2089. {
  2090. $html = '';
  2091. if ($this->parent_id != 0) {
  2092. $parent_question = self::read($this->parent_id);
  2093. $html = $parent_question->show_media_content();
  2094. } else {
  2095. $html .= Display::page_subheader($this->selectTitle());
  2096. $html .= $this->selectDescription();
  2097. }
  2098. return $html;
  2099. }
  2100. /**
  2101. * Swap between unique and multiple type answers.
  2102. *
  2103. * @return UniqueAnswer|MultipleAnswer
  2104. */
  2105. public function swapSimpleAnswerTypes()
  2106. {
  2107. $oppositeAnswers = [
  2108. UNIQUE_ANSWER => MULTIPLE_ANSWER,
  2109. MULTIPLE_ANSWER => UNIQUE_ANSWER,
  2110. ];
  2111. $this->type = $oppositeAnswers[$this->type];
  2112. Database::update(
  2113. Database::get_course_table(TABLE_QUIZ_QUESTION),
  2114. ['type' => $this->type],
  2115. ['c_id = ? AND id = ?' => [$this->course['real_id'], $this->id]]
  2116. );
  2117. $answerClasses = [
  2118. UNIQUE_ANSWER => 'UniqueAnswer',
  2119. MULTIPLE_ANSWER => 'MultipleAnswer',
  2120. ];
  2121. $swappedAnswer = new $answerClasses[$this->type]();
  2122. foreach ($this as $key => $value) {
  2123. $swappedAnswer->$key = $value;
  2124. }
  2125. return $swappedAnswer;
  2126. }
  2127. /**
  2128. * @param array $score
  2129. *
  2130. * @return bool
  2131. */
  2132. public function isQuestionWaitingReview($score)
  2133. {
  2134. $isReview = false;
  2135. if (!empty($score)) {
  2136. if (!empty($score['comments']) || $score['score'] > 0) {
  2137. $isReview = true;
  2138. }
  2139. }
  2140. return $isReview;
  2141. }
  2142. /**
  2143. * @param string $value
  2144. */
  2145. public function setFeedback($value)
  2146. {
  2147. $this->feedback = $value;
  2148. }
  2149. /**
  2150. * @param Exercise $exercise
  2151. *
  2152. * @return bool
  2153. */
  2154. public function showFeedback($exercise)
  2155. {
  2156. return
  2157. in_array($this->type, $this->questionTypeWithFeedback) &&
  2158. $exercise->getFeedbackType() != EXERCISE_FEEDBACK_TYPE_EXAM;
  2159. }
  2160. /**
  2161. * @return string
  2162. */
  2163. public function returnFormatFeedback()
  2164. {
  2165. return '<br />'.Display::return_message($this->feedback, 'normal', false);
  2166. }
  2167. /**
  2168. * Check if this question exists in another exercise.
  2169. *
  2170. * @throws \Doctrine\ORM\Query\QueryException
  2171. *
  2172. * @return bool
  2173. */
  2174. public function existsInAnotherExercise()
  2175. {
  2176. $count = $this->getCountExercise();
  2177. return $count > 1;
  2178. }
  2179. /**
  2180. * @throws \Doctrine\ORM\Query\QueryException
  2181. *
  2182. * @return int
  2183. */
  2184. public function getCountExercise()
  2185. {
  2186. $em = Database::getManager();
  2187. $count = $em
  2188. ->createQuery('
  2189. SELECT COUNT(qq.iid) FROM ChamiloCourseBundle:CQuizRelQuestion qq
  2190. WHERE qq.questionId = :id
  2191. ')
  2192. ->setParameters(['id' => (int) $this->id])
  2193. ->getSingleScalarResult();
  2194. return (int) $count;
  2195. }
  2196. /**
  2197. * Check if this question exists in another exercise.
  2198. *
  2199. * @throws \Doctrine\ORM\Query\QueryException
  2200. *
  2201. * @return mixed
  2202. */
  2203. public function getExerciseListWhereQuestionExists()
  2204. {
  2205. $em = Database::getManager();
  2206. $result = $em
  2207. ->createQuery('
  2208. SELECT e
  2209. FROM ChamiloCourseBundle:CQuizRelQuestion qq
  2210. JOIN ChamiloCourseBundle:CQuiz e
  2211. WHERE e.iid = qq.exerciceId AND qq.questionId = :id
  2212. ')
  2213. ->setParameters(['id' => (int) $this->id])
  2214. ->getResult();
  2215. return $result;
  2216. }
  2217. /**
  2218. * Resizes a picture || Warning!: can only be called after uploadPicture,
  2219. * or if picture is already available in object.
  2220. *
  2221. * @param string $Dimension - Resizing happens proportional according to given dimension: height|width|any
  2222. * @param int $Max - Maximum size
  2223. *
  2224. * @return bool|null - true if success, false if failed
  2225. *
  2226. * @author Toon Keppens
  2227. */
  2228. private function resizePicture($Dimension, $Max)
  2229. {
  2230. // if the question has an ID
  2231. if (!$this->id) {
  2232. return false;
  2233. }
  2234. $picturePath = $this->getHotSpotFolderInCourse().'/'.$this->getPictureFilename();
  2235. // Get dimensions from current image.
  2236. $my_image = new Image($picturePath);
  2237. $current_image_size = $my_image->get_image_size();
  2238. $current_width = $current_image_size['width'];
  2239. $current_height = $current_image_size['height'];
  2240. if ($current_width < $Max && $current_height < $Max) {
  2241. return true;
  2242. } elseif ($current_height == '') {
  2243. return false;
  2244. }
  2245. // Resize according to height.
  2246. if ($Dimension == "height") {
  2247. $resize_scale = $current_height / $Max;
  2248. $new_width = ceil($current_width / $resize_scale);
  2249. }
  2250. // Resize according to width
  2251. if ($Dimension == "width") {
  2252. $new_width = $Max;
  2253. }
  2254. // Resize according to height or width, both should not be larger than $Max after resizing.
  2255. if ($Dimension == "any") {
  2256. if ($current_height > $current_width || $current_height == $current_width) {
  2257. $resize_scale = $current_height / $Max;
  2258. $new_width = ceil($current_width / $resize_scale);
  2259. }
  2260. if ($current_height < $current_width) {
  2261. $new_width = $Max;
  2262. }
  2263. }
  2264. $my_image->resize($new_width);
  2265. $result = $my_image->send_image($picturePath);
  2266. if ($result) {
  2267. return true;
  2268. }
  2269. return false;
  2270. }
  2271. }