question.class.php 65 KB

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