question.class.php 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499
  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. }