question.class.php 67 KB

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