question.class.php 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539
  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. $extraField = new ExtraField('question');
  1565. $extraField->addElements($form, $this->iid);
  1566. // default values
  1567. $defaults = [];
  1568. $defaults['questionName'] = $this->question;
  1569. $defaults['questionDescription'] = $this->description;
  1570. $defaults['questionLevel'] = $this->level;
  1571. $defaults['questionCategory'] = $this->category;
  1572. $defaults['feedback'] = $this->feedback;
  1573. // Came from he question pool
  1574. if (isset($_GET['fromExercise'])) {
  1575. $form->setDefaults($defaults);
  1576. }
  1577. if (!isset($_GET['newQuestion']) || $isContent) {
  1578. $form->setDefaults($defaults);
  1579. }
  1580. /*if (!empty($_REQUEST['myid'])) {
  1581. $form->setDefaults($defaults);
  1582. } else {
  1583. if ($isContent == 1) {
  1584. $form->setDefaults($defaults);
  1585. }
  1586. }*/
  1587. }
  1588. /**
  1589. * function which process the creation of questions.
  1590. *
  1591. * @param FormValidator $form
  1592. * @param Exercise $exercise
  1593. */
  1594. public function processCreation($form, $exercise)
  1595. {
  1596. $this->updateTitle($form->getSubmitValue('questionName'));
  1597. $this->updateDescription($form->getSubmitValue('questionDescription'));
  1598. $this->updateLevel($form->getSubmitValue('questionLevel'));
  1599. $this->updateCategory($form->getSubmitValue('questionCategory'));
  1600. $this->setFeedback($form->getSubmitValue('feedback'));
  1601. //Save normal question if NOT media
  1602. if ($this->type != MEDIA_QUESTION) {
  1603. $this->save($exercise);
  1604. // modify the exercise
  1605. $exercise->addToList($this->id);
  1606. $exercise->update_question_positions();
  1607. $extraFieldValues = new ExtraFieldValue('question');
  1608. $extraFieldValues->saveFieldValues($form->exportValues());
  1609. }
  1610. }
  1611. /**
  1612. * abstract function which creates the form to create / edit the answers of the question.
  1613. *
  1614. * @param FormValidator $form
  1615. */
  1616. abstract public function createAnswersForm($form);
  1617. /**
  1618. * abstract function which process the creation of answers.
  1619. *
  1620. * @param FormValidator $form
  1621. * @param Exercise $exercise
  1622. */
  1623. abstract public function processAnswersCreation($form, $exercise);
  1624. /**
  1625. * Displays the menu of question types.
  1626. *
  1627. * @param Exercise $objExercise
  1628. */
  1629. public static function displayTypeMenu($objExercise)
  1630. {
  1631. $feedback_type = $objExercise->feedback_type;
  1632. $exerciseId = $objExercise->id;
  1633. // 1. by default we show all the question types
  1634. $question_type_custom_list = self::get_question_type_list();
  1635. if (!isset($feedback_type)) {
  1636. $feedback_type = 0;
  1637. }
  1638. if ($feedback_type == 1) {
  1639. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  1640. $question_type_custom_list = [
  1641. UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],
  1642. HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION],
  1643. ];
  1644. } else {
  1645. unset($question_type_custom_list[HOT_SPOT_DELINEATION]);
  1646. }
  1647. echo '<div class="panel panel-default">';
  1648. echo '<div class="panel-body">';
  1649. echo '<ul class="question_menu">';
  1650. foreach ($question_type_custom_list as $i => $a_type) {
  1651. // @todo remove require_once classes are already loaded using composer
  1652. // include the class of the type
  1653. require_once $a_type[0];
  1654. // get the picture of the type and the langvar which describes it
  1655. $img = $explanation = '';
  1656. eval('$img = '.$a_type[1].'::$typePicture;');
  1657. eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
  1658. echo '<li>';
  1659. echo '<div class="icon-image">';
  1660. $icon = '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.
  1661. Display::return_icon($img, $explanation, null, ICON_SIZE_BIG).'</a>';
  1662. if ($objExercise->force_edit_exercise_in_lp === false) {
  1663. if ($objExercise->exercise_was_added_in_lp == true) {
  1664. $img = pathinfo($img);
  1665. $img = $img['filename'].'_na.'.$img['extension'];
  1666. $icon = Display::return_icon($img, $explanation, null, ICON_SIZE_BIG);
  1667. }
  1668. }
  1669. echo $icon;
  1670. echo '</div>';
  1671. echo '</li>';
  1672. }
  1673. echo '<li>';
  1674. echo '<div class="icon_image_content">';
  1675. if ($objExercise->exercise_was_added_in_lp == true) {
  1676. echo Display::return_icon(
  1677. 'database_na.png',
  1678. get_lang('GetExistingQuestion'),
  1679. null,
  1680. ICON_SIZE_BIG
  1681. );
  1682. } else {
  1683. if ($feedback_type == 1) {
  1684. echo $url = "<a href=\"question_pool.php?".api_get_cidreq()."&type=1&fromExercise=$exerciseId\">";
  1685. } else {
  1686. echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&fromExercise='.$exerciseId.'">';
  1687. }
  1688. echo Display::return_icon(
  1689. 'database.png',
  1690. get_lang('GetExistingQuestion'),
  1691. null,
  1692. ICON_SIZE_BIG
  1693. );
  1694. }
  1695. echo '</a>';
  1696. echo '</div></li>';
  1697. echo '</ul>';
  1698. echo '</div>';
  1699. echo '</div>';
  1700. }
  1701. /**
  1702. * @param int $question_id
  1703. * @param string $name
  1704. * @param int $course_id
  1705. * @param int $position
  1706. *
  1707. * @return false|string
  1708. */
  1709. public static function saveQuestionOption($question_id, $name, $course_id, $position = 0)
  1710. {
  1711. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1712. $params['question_id'] = (int) $question_id;
  1713. $params['name'] = $name;
  1714. $params['position'] = $position;
  1715. $params['c_id'] = $course_id;
  1716. $result = self::readQuestionOption($question_id, $course_id);
  1717. $last_id = Database::insert($table, $params);
  1718. if ($last_id) {
  1719. $sql = "UPDATE $table SET id = iid WHERE iid = $last_id";
  1720. Database::query($sql);
  1721. }
  1722. return $last_id;
  1723. }
  1724. /**
  1725. * @param int $question_id
  1726. * @param int $course_id
  1727. */
  1728. public static function deleteAllQuestionOptions($question_id, $course_id)
  1729. {
  1730. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1731. Database::delete(
  1732. $table,
  1733. [
  1734. 'c_id = ? AND question_id = ?' => [
  1735. $course_id,
  1736. $question_id,
  1737. ],
  1738. ]
  1739. );
  1740. }
  1741. /**
  1742. * @param int $id
  1743. * @param array $params
  1744. * @param int $course_id
  1745. *
  1746. * @return bool|int
  1747. */
  1748. public static function updateQuestionOption($id, $params, $course_id)
  1749. {
  1750. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1751. $result = Database::update(
  1752. $table,
  1753. $params,
  1754. ['c_id = ? AND id = ?' => [$course_id, $id]]
  1755. );
  1756. return $result;
  1757. }
  1758. /**
  1759. * @param int $question_id
  1760. * @param int $course_id
  1761. *
  1762. * @return array
  1763. */
  1764. public static function readQuestionOption($question_id, $course_id)
  1765. {
  1766. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1767. $result = Database::select(
  1768. '*',
  1769. $table,
  1770. [
  1771. 'where' => [
  1772. 'c_id = ? AND question_id = ?' => [
  1773. $course_id,
  1774. $question_id,
  1775. ],
  1776. ],
  1777. 'order' => 'id ASC',
  1778. ]
  1779. );
  1780. return $result;
  1781. }
  1782. /**
  1783. * Shows question title an description.
  1784. *
  1785. * @param Exercise $exercise
  1786. * @param int $counter
  1787. * @param array $score
  1788. *
  1789. * @return string HTML string with the header of the question (before the answers table)
  1790. */
  1791. public function return_header(Exercise $exercise, $counter = null, $score = [])
  1792. {
  1793. $counterLabel = '';
  1794. if (!empty($counter)) {
  1795. $counterLabel = (int) $counter;
  1796. }
  1797. $scoreLabel = get_lang('Wrong');
  1798. if (in_array($exercise->results_disabled, [
  1799. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  1800. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  1801. ])
  1802. ) {
  1803. $scoreLabel = get_lang('QuizWrongAnswerHereIsTheCorrectOne');
  1804. }
  1805. $class = 'error';
  1806. if (isset($score['pass']) && $score['pass'] == true) {
  1807. $scoreLabel = get_lang('Correct');
  1808. if (in_array($exercise->results_disabled, [
  1809. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  1810. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  1811. ])
  1812. ) {
  1813. $scoreLabel = get_lang('CorrectAnswer');
  1814. }
  1815. $class = 'success';
  1816. }
  1817. switch ($this->type) {
  1818. case FREE_ANSWER:
  1819. case ORAL_EXPRESSION:
  1820. case ANNOTATION:
  1821. $score['revised'] = isset($score['revised']) ? $score['revised'] : false;
  1822. if ($score['revised'] == true) {
  1823. $scoreLabel = get_lang('Revised');
  1824. $class = '';
  1825. } else {
  1826. $scoreLabel = get_lang('NotRevised');
  1827. $class = 'warning';
  1828. if (isset($score['weight'])) {
  1829. $weight = float_format($score['weight'], 1);
  1830. $score['result'] = ' ? / '.$weight;
  1831. }
  1832. $model = ExerciseLib::getCourseScoreModel();
  1833. if (!empty($model)) {
  1834. $score['result'] = ' ? ';
  1835. }
  1836. $hide = api_get_configuration_value('hide_free_question_score');
  1837. if ($hide === true) {
  1838. $score['result'] = '-';
  1839. }
  1840. }
  1841. break;
  1842. case UNIQUE_ANSWER:
  1843. if (in_array($exercise->results_disabled, [
  1844. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  1845. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  1846. ])
  1847. ) {
  1848. if (isset($score['user_answered'])) {
  1849. if ($score['user_answered'] === false) {
  1850. $scoreLabel = get_lang('Unanswered');
  1851. $class = 'info';
  1852. }
  1853. }
  1854. }
  1855. break;
  1856. }
  1857. // display question category, if any
  1858. $header = '';
  1859. if ($exercise->display_category_name) {
  1860. $header = TestCategory::returnCategoryAndTitle($this->id);
  1861. }
  1862. $show_media = '';
  1863. if ($show_media) {
  1864. $header .= $this->show_media_content();
  1865. }
  1866. $scoreCurrent = [
  1867. 'used' => isset($score['score']) ? $score['score'] : '',
  1868. 'missing' => isset($score['weight']) ? $score['weight'] : '',
  1869. ];
  1870. $header .= Display::page_subheader2($counterLabel.'. '.$this->question);
  1871. // dont display score for certainty degree questions
  1872. if ($this->type != MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  1873. if (isset($score['result'])) {
  1874. if (in_array($exercise->results_disabled, [
  1875. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  1876. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  1877. ])
  1878. ) {
  1879. $score['result'] = null;
  1880. }
  1881. $header .= $exercise->getQuestionRibbon($class, $scoreLabel, $score['result'], $scoreCurrent);
  1882. }
  1883. }
  1884. if ($this->type != READING_COMPREHENSION) {
  1885. // Do not show the description (the text to read) if the question is of type READING_COMPREHENSION
  1886. $header .= Display::div(
  1887. $this->description,
  1888. ['class' => 'question_description']
  1889. );
  1890. } else {
  1891. if ($score['pass'] == true) {
  1892. $message = Display::div(
  1893. sprintf(
  1894. get_lang('ReadingQuestionCongratsSpeedXReachedForYWords'),
  1895. ReadingComprehension::$speeds[$this->level],
  1896. $this->getWordsCount()
  1897. )
  1898. );
  1899. } else {
  1900. $message = Display::div(
  1901. sprintf(
  1902. get_lang('ReadingQuestionCongratsSpeedXNotReachedForYWords'),
  1903. ReadingComprehension::$speeds[$this->level],
  1904. $this->getWordsCount()
  1905. )
  1906. );
  1907. }
  1908. $header .= $message.'<br />';
  1909. }
  1910. if (isset($score['pass']) && $score['pass'] === false) {
  1911. if ($this->showFeedback($exercise)) {
  1912. $header .= $this->returnFormatFeedback();
  1913. }
  1914. }
  1915. return $header;
  1916. }
  1917. /**
  1918. * @deprecated
  1919. * Create a question from a set of parameters.
  1920. *
  1921. * @param int Quiz ID
  1922. * @param string Question name
  1923. * @param int Maximum result for the question
  1924. * @param int Type of question (see constants at beginning of question.class.php)
  1925. * @param int Question level/category
  1926. * @param string $quiz_id
  1927. */
  1928. public function create_question(
  1929. $quiz_id,
  1930. $question_name,
  1931. $question_description = '',
  1932. $max_score = 0,
  1933. $type = 1,
  1934. $level = 1
  1935. ) {
  1936. $course_id = api_get_course_int_id();
  1937. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1938. $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1939. $quiz_id = intval($quiz_id);
  1940. $max_score = (float) $max_score;
  1941. $type = intval($type);
  1942. $level = intval($level);
  1943. // Get the max position
  1944. $sql = "SELECT max(position) as max_position
  1945. FROM $tbl_quiz_question q
  1946. INNER JOIN $tbl_quiz_rel_question r
  1947. ON
  1948. q.id = r.question_id AND
  1949. exercice_id = $quiz_id AND
  1950. q.c_id = $course_id AND
  1951. r.c_id = $course_id";
  1952. $rs_max = Database::query($sql);
  1953. $row_max = Database::fetch_object($rs_max);
  1954. $max_position = $row_max->max_position + 1;
  1955. $params = [
  1956. 'c_id' => $course_id,
  1957. 'question' => $question_name,
  1958. 'description' => $question_description,
  1959. 'ponderation' => $max_score,
  1960. 'position' => $max_position,
  1961. 'type' => $type,
  1962. 'level' => $level,
  1963. ];
  1964. $question_id = Database::insert($tbl_quiz_question, $params);
  1965. if ($question_id) {
  1966. $sql = "UPDATE $tbl_quiz_question
  1967. SET id = iid WHERE iid = $question_id";
  1968. Database::query($sql);
  1969. // Get the max question_order
  1970. $sql = "SELECT max(question_order) as max_order
  1971. FROM $tbl_quiz_rel_question
  1972. WHERE c_id = $course_id AND exercice_id = $quiz_id ";
  1973. $rs_max_order = Database::query($sql);
  1974. $row_max_order = Database::fetch_object($rs_max_order);
  1975. $max_order = $row_max_order->max_order + 1;
  1976. // Attach questions to quiz
  1977. $sql = "INSERT INTO $tbl_quiz_rel_question (c_id, question_id, exercice_id, question_order)
  1978. VALUES($course_id, $question_id, $quiz_id, $max_order)";
  1979. Database::query($sql);
  1980. }
  1981. return $question_id;
  1982. }
  1983. /**
  1984. * @return array the image filename of the question type
  1985. */
  1986. public function get_type_icon_html()
  1987. {
  1988. $type = $this->selectType();
  1989. $tabQuestionList = self::get_question_type_list(); // [0]=file to include [1]=type name
  1990. require_once $tabQuestionList[$type][0];
  1991. $img = $explanation = null;
  1992. eval('$img = '.$tabQuestionList[$type][1].'::$typePicture;');
  1993. eval('$explanation = get_lang('.$tabQuestionList[$type][1].'::$explanationLangVar);');
  1994. return [$img, $explanation];
  1995. }
  1996. /**
  1997. * Get course medias.
  1998. *
  1999. * @param int course id
  2000. * @param int $course_id
  2001. *
  2002. * @return array
  2003. */
  2004. public static function get_course_medias(
  2005. $course_id,
  2006. $start = 0,
  2007. $limit = 100,
  2008. $sidx = "question",
  2009. $sord = "ASC",
  2010. $where_condition = []
  2011. ) {
  2012. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2013. $default_where = [
  2014. 'c_id = ? AND parent_id = 0 AND type = ?' => [
  2015. $course_id,
  2016. MEDIA_QUESTION,
  2017. ],
  2018. ];
  2019. $result = Database::select(
  2020. '*',
  2021. $table_question,
  2022. [
  2023. 'limit' => " $start, $limit",
  2024. 'where' => $default_where,
  2025. 'order' => "$sidx $sord",
  2026. ]
  2027. );
  2028. return $result;
  2029. }
  2030. /**
  2031. * Get count course medias.
  2032. *
  2033. * @param int course id
  2034. *
  2035. * @return int
  2036. */
  2037. public static function get_count_course_medias($course_id)
  2038. {
  2039. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2040. $result = Database::select(
  2041. 'count(*) as count',
  2042. $table_question,
  2043. [
  2044. 'where' => [
  2045. 'c_id = ? AND parent_id = 0 AND type = ?' => [
  2046. $course_id,
  2047. MEDIA_QUESTION,
  2048. ],
  2049. ],
  2050. ],
  2051. 'first'
  2052. );
  2053. if ($result && isset($result['count'])) {
  2054. return $result['count'];
  2055. }
  2056. return 0;
  2057. }
  2058. /**
  2059. * @param int $course_id
  2060. *
  2061. * @return array
  2062. */
  2063. public static function prepare_course_media_select($course_id)
  2064. {
  2065. $medias = self::get_course_medias($course_id);
  2066. $media_list = [];
  2067. $media_list[0] = get_lang('NoMedia');
  2068. if (!empty($medias)) {
  2069. foreach ($medias as $media) {
  2070. $media_list[$media['id']] = empty($media['question']) ? get_lang('Untitled') : $media['question'];
  2071. }
  2072. }
  2073. return $media_list;
  2074. }
  2075. /**
  2076. * @return array
  2077. */
  2078. public static function get_default_levels()
  2079. {
  2080. $levels = [
  2081. 1 => 1,
  2082. 2 => 2,
  2083. 3 => 3,
  2084. 4 => 4,
  2085. 5 => 5,
  2086. ];
  2087. return $levels;
  2088. }
  2089. /**
  2090. * @return string
  2091. */
  2092. public function show_media_content()
  2093. {
  2094. $html = '';
  2095. if ($this->parent_id != 0) {
  2096. $parent_question = self::read($this->parent_id);
  2097. $html = $parent_question->show_media_content();
  2098. } else {
  2099. $html .= Display::page_subheader($this->selectTitle());
  2100. $html .= $this->selectDescription();
  2101. }
  2102. return $html;
  2103. }
  2104. /**
  2105. * Swap between unique and multiple type answers.
  2106. *
  2107. * @return UniqueAnswer|MultipleAnswer
  2108. */
  2109. public function swapSimpleAnswerTypes()
  2110. {
  2111. $oppositeAnswers = [
  2112. UNIQUE_ANSWER => MULTIPLE_ANSWER,
  2113. MULTIPLE_ANSWER => UNIQUE_ANSWER,
  2114. ];
  2115. $this->type = $oppositeAnswers[$this->type];
  2116. Database::update(
  2117. Database::get_course_table(TABLE_QUIZ_QUESTION),
  2118. ['type' => $this->type],
  2119. ['c_id = ? AND id = ?' => [$this->course['real_id'], $this->id]]
  2120. );
  2121. $answerClasses = [
  2122. UNIQUE_ANSWER => 'UniqueAnswer',
  2123. MULTIPLE_ANSWER => 'MultipleAnswer',
  2124. ];
  2125. $swappedAnswer = new $answerClasses[$this->type]();
  2126. foreach ($this as $key => $value) {
  2127. $swappedAnswer->$key = $value;
  2128. }
  2129. return $swappedAnswer;
  2130. }
  2131. /**
  2132. * @param array $score
  2133. *
  2134. * @return bool
  2135. */
  2136. public function isQuestionWaitingReview($score)
  2137. {
  2138. $isReview = false;
  2139. if (!empty($score)) {
  2140. if (!empty($score['comments']) || $score['score'] > 0) {
  2141. $isReview = true;
  2142. }
  2143. }
  2144. return $isReview;
  2145. }
  2146. /**
  2147. * @param string $value
  2148. */
  2149. public function setFeedback($value)
  2150. {
  2151. $this->feedback = $value;
  2152. }
  2153. /**
  2154. * @param Exercise $exercise
  2155. *
  2156. * @return bool
  2157. */
  2158. public function showFeedback($exercise)
  2159. {
  2160. return
  2161. in_array($this->type, $this->questionTypeWithFeedback) &&
  2162. $exercise->feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM;
  2163. }
  2164. /**
  2165. * @return string
  2166. */
  2167. public function returnFormatFeedback()
  2168. {
  2169. return '<br />'.Display::return_message($this->feedback, 'normal', false);
  2170. }
  2171. /**
  2172. * Check if this question exists in another exercise.
  2173. *
  2174. * @throws \Doctrine\ORM\Query\QueryException
  2175. *
  2176. * @return bool
  2177. */
  2178. public function existsInAnotherExercise()
  2179. {
  2180. $count = $this->getCountExercise();
  2181. return $count > 1;
  2182. }
  2183. /**
  2184. * @throws \Doctrine\ORM\Query\QueryException
  2185. *
  2186. * @return int
  2187. */
  2188. public function getCountExercise()
  2189. {
  2190. $em = Database::getManager();
  2191. $count = $em
  2192. ->createQuery('
  2193. SELECT COUNT(qq.iid) FROM ChamiloCourseBundle:CQuizRelQuestion qq
  2194. WHERE qq.questionId = :id
  2195. ')
  2196. ->setParameters(['id' => (int) $this->id])
  2197. ->getSingleScalarResult();
  2198. return (int) $count;
  2199. }
  2200. /**
  2201. * Check if this question exists in another exercise.
  2202. *
  2203. * @throws \Doctrine\ORM\Query\QueryException
  2204. *
  2205. * @return mixed
  2206. */
  2207. public function getExerciseListWhereQuestionExists()
  2208. {
  2209. $em = Database::getManager();
  2210. $result = $em
  2211. ->createQuery('
  2212. SELECT e
  2213. FROM ChamiloCourseBundle:CQuizRelQuestion qq
  2214. JOIN ChamiloCourseBundle:CQuiz e
  2215. WHERE e.iid = qq.exerciceId AND qq.questionId = :id
  2216. ')
  2217. ->setParameters(['id' => (int) $this->id])
  2218. ->getResult();
  2219. return $result;
  2220. }
  2221. /**
  2222. * Resizes a picture || Warning!: can only be called after uploadPicture,
  2223. * or if picture is already available in object.
  2224. *
  2225. * @param string $Dimension - Resizing happens proportional according to given dimension: height|width|any
  2226. * @param int $Max - Maximum size
  2227. *
  2228. * @return bool|null - true if success, false if failed
  2229. *
  2230. * @author Toon Keppens
  2231. */
  2232. private function resizePicture($Dimension, $Max)
  2233. {
  2234. // if the question has an ID
  2235. if (!$this->id) {
  2236. return false;
  2237. }
  2238. $picturePath = $this->getHotSpotFolderInCourse().'/'.$this->getPictureFilename();
  2239. // Get dimensions from current image.
  2240. $my_image = new Image($picturePath);
  2241. $current_image_size = $my_image->get_image_size();
  2242. $current_width = $current_image_size['width'];
  2243. $current_height = $current_image_size['height'];
  2244. if ($current_width < $Max && $current_height < $Max) {
  2245. return true;
  2246. } elseif ($current_height == '') {
  2247. return false;
  2248. }
  2249. // Resize according to height.
  2250. if ($Dimension == "height") {
  2251. $resize_scale = $current_height / $Max;
  2252. $new_width = ceil($current_width / $resize_scale);
  2253. }
  2254. // Resize according to width
  2255. if ($Dimension == "width") {
  2256. $new_width = $Max;
  2257. }
  2258. // Resize according to height or width, both should not be larger than $Max after resizing.
  2259. if ($Dimension == "any") {
  2260. if ($current_height > $current_width || $current_height == $current_width) {
  2261. $resize_scale = $current_height / $Max;
  2262. $new_width = ceil($current_width / $resize_scale);
  2263. }
  2264. if ($current_height < $current_width) {
  2265. $new_width = $Max;
  2266. }
  2267. }
  2268. $my_image->resize($new_width);
  2269. $result = $my_image->send_image($picturePath);
  2270. if ($result) {
  2271. return true;
  2272. }
  2273. return false;
  2274. }
  2275. }