question.class.php 66 KB

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