question.class.php 68 KB

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