question.class.php 78 KB

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