question.class.php 67 KB

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