question.class.php 74 KB

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