question.class.php 66 KB

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