question.class.php 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  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. /**
  14. * QUESTION CLASS
  15. *
  16. * This class allows to instantiate an object of type Question
  17. *
  18. * @author Olivier Brouckaert, original author
  19. * @author Patrick Cool, LaTeX support
  20. * @package chamilo.exercise
  21. */
  22. abstract class Question
  23. {
  24. public $id;
  25. public $question;
  26. public $description;
  27. public $weighting;
  28. public $position;
  29. public $type;
  30. public $level;
  31. public $picture;
  32. public $exerciseList; // array with the list of exercises which this question is in
  33. public $category_list;
  34. public $parent_id;
  35. public $isContent;
  36. public $course;
  37. public static $typePicture = 'new_question.png';
  38. public static $explanationLangVar = '';
  39. public $question_table_class = 'table table-striped';
  40. public $editionMode = 'normal';
  41. public $exercise; // exercise obj
  42. public $setDefaultValues = false;
  43. public $submitClass;
  44. public $submitText;
  45. public $setDefaultQuestionValues = false;
  46. public $c_id = null;
  47. public static $questionTypes = array(
  48. UNIQUE_ANSWER => array('unique_answer.class.php', 'UniqueAnswer'),
  49. MULTIPLE_ANSWER => array('multiple_answer.class.php', 'MultipleAnswer'),
  50. FILL_IN_BLANKS => array('fill_blanks.class.php', 'FillBlanks'),
  51. MATCHING => array('matching.class.php', 'Matching'),
  52. FREE_ANSWER => array('freeanswer.class.php', 'FreeAnswer'),
  53. ORAL_EXPRESSION => array('oral_expression.class.php', 'OralExpression'),
  54. HOT_SPOT => array('hotspot.class.php', 'HotSpot'),
  55. HOT_SPOT_DELINEATION => array('hotspot.class.php', 'HotspotDelineation'),
  56. MULTIPLE_ANSWER_COMBINATION => array('multiple_answer_combination.class.php', 'MultipleAnswerCombination' ),
  57. UNIQUE_ANSWER_NO_OPTION => array('unique_answer_no_option.class.php', 'UniqueAnswerNoOption'),
  58. MULTIPLE_ANSWER_TRUE_FALSE => array('multiple_answer_true_false.class.php', 'MultipleAnswerTrueFalse'),
  59. MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE => array('multiple_answer_combination_true_false.class.php', 'MultipleAnswerCombinationTrueFalse'),
  60. GLOBAL_MULTIPLE_ANSWER => array('global_multiple_answer.class.php', 'GlobalMultipleAnswer'),
  61. MEDIA_QUESTION => array('media_question.class.php', 'MediaQuestion'),
  62. UNIQUE_ANSWER_IMAGE => array('unique_answer_image.class.php', 'UniqueAnswerImage'),
  63. DRAGGABLE => array('draggable.class.php', 'Draggable')
  64. );
  65. /**
  66. * constructor of the class
  67. *
  68. * @author - Olivier Brouckaert
  69. */
  70. public function Question()
  71. {
  72. $this->id = 0;
  73. $this->question = '';
  74. $this->description = '';
  75. $this->weighting = 0;
  76. $this->position = 1;
  77. $this->picture = '';
  78. $this->level = 1;
  79. // This variable is used when loading an exercise like an scenario
  80. //with an special hotspot: final_overlap, final_missing, final_excess
  81. $this->extra = '';
  82. $this->exerciseList = array();
  83. $this->course = api_get_course_info();
  84. $this->category_list = array();
  85. $this->parent_id = 0;
  86. $this->editionMode = 'normal';
  87. }
  88. public function getIsContent()
  89. {
  90. $isContent = null;
  91. if (isset($_REQUEST['isContent'])) {
  92. $isContent = intval($_REQUEST['isContent']);
  93. }
  94. return $this->isContent = $isContent;
  95. }
  96. /**
  97. * @param string $title
  98. * @param int $course_id
  99. * @return mixed|bool
  100. */
  101. public function readByTitle($title, $course_id = null)
  102. {
  103. if (!empty($course_id)) {
  104. $course_info = api_get_course_info_by_id($course_id);
  105. } else {
  106. $course_info = api_get_course_info();
  107. }
  108. $course_id = $course_info['real_id'];
  109. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  110. $title = Database::escape_string($title);
  111. $sql = "SELECT iid FROM $TBL_QUESTIONS WHERE question = '$title' AND c_id = $course_id ";
  112. $result = Database::query($sql);
  113. if (Database::num_rows($result)) {
  114. $row = Database::fetch_array($result);
  115. return self::read($row['iid'], $course_id);
  116. }
  117. return false;
  118. }
  119. /**
  120. * Reads question informations from the data base
  121. *
  122. * @author Olivier Brouckaert
  123. * @param int $id - question ID
  124. * @param int $course_id
  125. * @param Exercise
  126. *
  127. * @return boolean - true if question exists, otherwise false
  128. */
  129. public static function read($id, $course_id = null, Exercise $exercise = null)
  130. {
  131. $id = intval($id);
  132. if (!empty($course_id)) {
  133. $course_info = api_get_course_info_by_id($course_id);
  134. } else {
  135. $course_info = api_get_course_info();
  136. }
  137. $course_id = $course_info['real_id'];
  138. if (empty($course_id) || $course_id == -1) {
  139. //return false;
  140. }
  141. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  142. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  143. $sql = "SELECT * FROM $TBL_QUESTIONS WHERE iid = $id";
  144. $result = Database::query($sql);
  145. // if the question has been found
  146. if ($object = Database::fetch_object($result)) {
  147. $objQuestion = Question::getInstance($object->type);
  148. if (!empty($objQuestion)) {
  149. $objQuestion->id = $id;
  150. $objQuestion->question = $object->question;
  151. $objQuestion->description = $object->description;
  152. $objQuestion->weighting = $object->ponderation;
  153. $objQuestion->position = $object->position;
  154. $objQuestion->type = $object->type;
  155. $objQuestion->picture = $object->picture;
  156. $objQuestion->level = (int)$object->level;
  157. $objQuestion->extra = $object->extra;
  158. $objQuestion->course = $course_info;
  159. $objQuestion->parent_id = $object->parent_id;
  160. $objQuestion->category_list = Testcategory::getCategoryForQuestion($id);
  161. $objQuestion->exercise = $exercise;
  162. $objQuestion->c_id = $object->c_id;
  163. $sql = "SELECT exercice_id FROM $TBL_EXERCICE_QUESTION WHERE question_id = $id";
  164. $result_exercise_list = Database::query($sql);
  165. // fills the array with the exercises which this question is in
  166. if ($result_exercise_list) {
  167. while ($obj = Database::fetch_object($result_exercise_list)) {
  168. $objQuestion->exerciseList[] = $obj->exercice_id;
  169. }
  170. }
  171. return $objQuestion;
  172. }
  173. }
  174. // question not found
  175. return false;
  176. }
  177. public function setEditionMode($mode)
  178. {
  179. $this->editionMode = $mode;
  180. }
  181. public function getEditionMode()
  182. {
  183. return $this->editionMode;
  184. }
  185. /**
  186. * Returns the question ID
  187. *
  188. * @author - Olivier Brouckaert
  189. * @return int - question ID
  190. */
  191. public function selectId()
  192. {
  193. return $this->id;
  194. }
  195. /**
  196. * Returns the question title
  197. *
  198. * @author - Olivier Brouckaert
  199. * @return string - question title
  200. */
  201. public function selectTitle()
  202. {
  203. return $this->question;
  204. }
  205. /**
  206. * returns the question description
  207. *
  208. * @author - Olivier Brouckaert
  209. * @return string - question description
  210. */
  211. public function selectDescription()
  212. {
  213. $this->description = $this->description;
  214. return $this->description;
  215. }
  216. /**
  217. * returns the question weighting
  218. *
  219. * @author - Olivier Brouckaert
  220. * @return int - question weighting
  221. */
  222. public function selectWeighting()
  223. {
  224. return $this->weighting;
  225. }
  226. /**
  227. * returns the question position
  228. *
  229. * @author - Olivier Brouckaert
  230. * @return int - question position
  231. */
  232. public function selectPosition()
  233. {
  234. return $this->position;
  235. }
  236. /**
  237. * returns the answer type
  238. *
  239. * @author - Olivier Brouckaert
  240. * @return int - answer type
  241. */
  242. public function selectType()
  243. {
  244. return $this->type;
  245. }
  246. /**
  247. * returns the level of the question
  248. *
  249. * @author - Nicolas Raynaud
  250. * @return int - level of the question, 0 by default.
  251. */
  252. public function selectLevel()
  253. {
  254. return $this->level;
  255. }
  256. /**
  257. * returns the picture name
  258. *
  259. * @author - Olivier Brouckaert
  260. * @return string - picture name
  261. */
  262. public function selectPicture()
  263. {
  264. return $this->picture;
  265. }
  266. public function selectPicturePath()
  267. {
  268. if (!empty($this->picture)) {
  269. return api_get_path(WEB_COURSE_PATH).$this->course['path'].'/document/images/'.$this->picture;
  270. }
  271. return false;
  272. }
  273. /**
  274. * returns the array with the exercise ID list
  275. *
  276. * @author - Olivier Brouckaert
  277. * @return array - list of exercise ID which the question is in
  278. */
  279. public function selectExerciseList()
  280. {
  281. return $this->exerciseList;
  282. }
  283. /**
  284. * returns the number of exercises which this question is in
  285. *
  286. * @author - Olivier Brouckaert
  287. * @return integer - number of exercises
  288. */
  289. public function selectNbrExercises()
  290. {
  291. return sizeof($this->exerciseList);
  292. }
  293. /**
  294. * @param $course_id
  295. */
  296. public function updateCourse($course_id)
  297. {
  298. $this->course = api_get_course_info_by_id($course_id);
  299. }
  300. /**
  301. * changes the question title
  302. *
  303. * @author - Olivier Brouckaert
  304. * @param - string $title - question title
  305. */
  306. public function updateTitle($title)
  307. {
  308. $this->question = $title;
  309. }
  310. public function updateParentId($id)
  311. {
  312. $this->parent_id = intval($id);
  313. }
  314. /**
  315. * changes the question description
  316. *
  317. * @author - Olivier Brouckaert
  318. * @param - string $description - question description
  319. */
  320. public function updateDescription($description)
  321. {
  322. $this->description = $description;
  323. }
  324. /**
  325. * changes the question weighting
  326. *
  327. * @author - Olivier Brouckaert
  328. * @param - integer $weighting - question weighting
  329. */
  330. public function updateWeighting($weighting)
  331. {
  332. $this->weighting = $weighting;
  333. }
  334. /**
  335. * @author - Hubert Borderiou 12-10-2011
  336. * @param - array of category $in_category
  337. */
  338. public function updateCategory($category_list)
  339. {
  340. $this->category_list = $category_list;
  341. }
  342. /**
  343. * @author - Hubert Borderiou 12-10-2011
  344. * @param - interger $in_positive
  345. */
  346. public function updateScoreAlwaysPositive($in_positive)
  347. {
  348. $this->scoreAlwaysPositive = $in_positive;
  349. }
  350. /**
  351. * @author - Hubert Borderiou 12-10-2011
  352. * @param - interger $in_positive
  353. */
  354. public function updateUncheckedMayScore($in_positive)
  355. {
  356. $this->uncheckedMayScore = $in_positive;
  357. }
  358. /**
  359. * Save category of a question
  360. *
  361. * A question can have n categories
  362. * if category is empty, then question has no category then delete the category entry
  363. *
  364. * @param - int $in_positive
  365. * @author - Julio Montoya - Adding multiple cat support
  366. */
  367. public function saveCategories($category_list)
  368. {
  369. $course_id = $this->course['real_id'];
  370. if (!empty($category_list)) {
  371. $this->deleteCategory();
  372. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  373. $category_list = array_filter($category_list);
  374. // update or add category for a question
  375. foreach ($category_list as $category_id) {
  376. if (empty($category_id)) {
  377. continue;
  378. }
  379. $category_id = intval($category_id);
  380. $question_id = Database::escape_string($this->id);
  381. $sql = "SELECT count(*) AS nb FROM $TBL_QUESTION_REL_CATEGORY
  382. WHERE category_id = $category_id AND question_id = $question_id AND c_id=".$course_id;
  383. $res = Database::query($sql);
  384. $row = Database::fetch_array($res);
  385. if ($row['nb'] > 0) {
  386. //DO nothing
  387. //$sql = "UPDATE $TBL_QUESTION_REL_CATEGORY SET category_id = $category_id WHERE question_id=$question_id AND c_id=".api_get_course_int_id();
  388. //$res = Database::query($sql);
  389. } else {
  390. $sql = "INSERT INTO $TBL_QUESTION_REL_CATEGORY (c_id, question_id, category_id) VALUES (".$course_id.", $question_id, $category_id)";
  391. Database::query($sql);
  392. }
  393. }
  394. }
  395. }
  396. /**
  397. * @author - Hubert Borderiou 12-10-2011
  398. * @param - interger $in_positive
  399. * in this version, a question can only have 1 category
  400. * if category is 0, then question has no category then delete the category entry
  401. */
  402. public function saveCategory($in_category)
  403. {
  404. if ($in_category <= 0) {
  405. $this->deleteCategory();
  406. } else {
  407. // update or add category for a question
  408. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  409. $category_id = Database::escape_string($in_category);
  410. $question_id = Database::escape_string($this->id);
  411. $sql = "SELECT count(*) AS nb FROM $TBL_QUESTION_REL_CATEGORY WHERE question_id= $question_id AND c_id=".api_get_course_int_id(
  412. );
  413. $res = Database::query($sql);
  414. $row = Database::fetch_array($res);
  415. if ($row['nb'] > 0) {
  416. $sql = "UPDATE $TBL_QUESTION_REL_CATEGORY SET category_id= $category_id WHERE question_id=$question_id AND c_id=".api_get_course_int_id(
  417. );
  418. $res = Database::query($sql);
  419. } else {
  420. $sql = "INSERT INTO $TBL_QUESTION_REL_CATEGORY VALUES (".api_get_course_int_id(
  421. ).", $question_id, $category_id)";
  422. $res = Database::query($sql);
  423. }
  424. }
  425. }
  426. /**
  427. * @author hubert borderiou 12-10-2011
  428. * delete any category entry for question id
  429. * @param : none
  430. * delte the category for question
  431. */
  432. public function deleteCategory()
  433. {
  434. $course_id = $this->course['real_id'];
  435. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  436. $question_id = Database::escape_string($this->id);
  437. $sql = "DELETE FROM $TBL_QUESTION_REL_CATEGORY WHERE question_id = $question_id AND c_id = ".$course_id;
  438. Database::query($sql);
  439. }
  440. /**
  441. * changes the question position
  442. *
  443. * @author - Olivier Brouckaert
  444. * @param - integer $position - question position
  445. */
  446. public function updatePosition($position)
  447. {
  448. $this->position = $position;
  449. }
  450. /**
  451. * changes the question level
  452. *
  453. * @author - Nicolas Raynaud
  454. * @param - integer $level - question level
  455. */
  456. public function updateLevel($level)
  457. {
  458. $this->level = $level;
  459. }
  460. /**
  461. * changes the answer type. If the user changes the type from "unique answer" to "multiple answers"
  462. * (or conversely) answers are not deleted, otherwise yes
  463. *
  464. * @author - Olivier Brouckaert
  465. * @param - integer $type - answer type
  466. */
  467. public function updateType($type)
  468. {
  469. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  470. $course_id = $this->course['real_id'];
  471. if (empty($course_id)) {
  472. $course_id = api_get_course_int_id();
  473. }
  474. // if we really change the type
  475. if ($type != $this->type) {
  476. // if we don't change from "unique answer" to "multiple answers" (or conversely)
  477. if (!in_array($this->type, array(UNIQUE_ANSWER, MULTIPLE_ANSWER)) || !in_array(
  478. $type,
  479. array(UNIQUE_ANSWER, MULTIPLE_ANSWER)
  480. )
  481. ) {
  482. // removes old answers
  483. $sql = "DELETE FROM $TBL_REPONSES WHERE question_id='".Database::escape_string($this->id)."'";
  484. Database::query($sql);
  485. }
  486. $this->type = $type;
  487. }
  488. }
  489. /**
  490. * Adds a picture to the question
  491. *
  492. * @author - Olivier Brouckaert
  493. * @param - string $Picture - temporary path of the picture to upload
  494. * @param - string $PictureName - Name of the picture
  495. * @return - boolean - true if uploaded, otherwise false
  496. */
  497. public function uploadPicture($Picture, $PictureName, $picturePath = null)
  498. {
  499. if (empty($picturePath)) {
  500. global $picturePath;
  501. }
  502. if (!file_exists($picturePath)) {
  503. if (mkdir($picturePath, api_get_permissions_for_new_directories())) {
  504. // document path
  505. $documentPath = api_get_path(SYS_COURSE_PATH).$this->course['path']."/document";
  506. $path = str_replace($documentPath, '', $picturePath);
  507. $title_path = basename($picturePath);
  508. $doc_id = FileManager::add_document($this->course, $path, 'folder', 0, $title_path);
  509. api_item_property_update($this->course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
  510. }
  511. }
  512. // if the question has got an ID
  513. if ($this->id) {
  514. $extension = pathinfo($PictureName, PATHINFO_EXTENSION);
  515. $this->picture = 'quiz-'.$this->id.'.jpg';
  516. $o_img = new Image($Picture);
  517. $o_img->send_image($picturePath.'/'.$this->picture, -1, 'jpg');
  518. $document_id = FileManager::add_document(
  519. $this->course,
  520. '/images/'.$this->picture,
  521. 'file',
  522. filesize($picturePath.'/'.$this->picture),
  523. $this->picture
  524. );
  525. if ($document_id) {
  526. return api_item_property_update(
  527. $this->course,
  528. TOOL_DOCUMENT,
  529. $document_id,
  530. 'DocumentAdded',
  531. api_get_user_id()
  532. );
  533. }
  534. }
  535. return false;
  536. }
  537. /**
  538. * Resizes a picture || Warning!: can only be called after uploadPicture, or if picture is already available in object.
  539. *
  540. * @author - Toon Keppens
  541. * @param - string $Dimension - Resizing happens proportional according to given dimension: height|width|any
  542. * @param - integer $Max - Maximum size
  543. * @return - boolean - true if success, false if failed
  544. */
  545. function resizePicture($Dimension, $Max)
  546. {
  547. global $picturePath;
  548. // if the question has an ID
  549. if ($this->id) {
  550. // Get dimensions from current image.
  551. $my_image = new Image($picturePath.'/'.$this->picture);
  552. $current_image_size = $my_image->get_image_size();
  553. $current_width = $current_image_size['width'];
  554. $current_height = $current_image_size['height'];
  555. if ($current_width < $Max && $current_height < $Max) {
  556. return true;
  557. } elseif ($current_height == "") {
  558. return false;
  559. }
  560. // Resize according to height.
  561. if ($Dimension == "height") {
  562. $resize_scale = $current_height / $Max;
  563. $new_height = $Max;
  564. $new_width = ceil($current_width / $resize_scale);
  565. }
  566. // Resize according to width
  567. if ($Dimension == "width") {
  568. $resize_scale = $current_width / $Max;
  569. $new_width = $Max;
  570. $new_height = ceil($current_height / $resize_scale);
  571. }
  572. // Resize according to height or width, both should not be larger than $Max after resizing.
  573. if ($Dimension == "any") {
  574. if ($current_height > $current_width || $current_height == $current_width) {
  575. $resize_scale = $current_height / $Max;
  576. $new_height = $Max;
  577. $new_width = ceil($current_width / $resize_scale);
  578. }
  579. if ($current_height < $current_width) {
  580. $resize_scale = $current_width / $Max;
  581. $new_width = $Max;
  582. $new_height = ceil($current_height / $resize_scale);
  583. }
  584. }
  585. $my_image->resize($new_width, $new_height);
  586. $result = $my_image->send_image($picturePath.'/'.$this->picture);
  587. if ($result) {
  588. return true;
  589. } else {
  590. return false;
  591. }
  592. }
  593. }
  594. /**
  595. * deletes the picture
  596. *
  597. * @author - Olivier Brouckaert
  598. * @return - boolean - true if removed, otherwise false
  599. */
  600. function removePicture()
  601. {
  602. global $picturePath;
  603. // if the question has got an ID and if the picture exists
  604. if ($this->id) {
  605. $picture = $this->picture;
  606. $this->picture = '';
  607. return @unlink($picturePath.'/'.$picture) ? true : false;
  608. }
  609. return false;
  610. }
  611. /**
  612. * Exports a picture to another question
  613. *
  614. * @author - Olivier Brouckaert
  615. * @param - integer $questionId - ID of the target question
  616. * @return - boolean - true if copied, otherwise false
  617. */
  618. function exportPicture($questionId, $course_info)
  619. {
  620. $course_id = $course_info['real_id'];
  621. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  622. $destination_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/images';
  623. $source_path = api_get_path(SYS_COURSE_PATH).$this->course['path'].'/document/images';
  624. // if the question has got an ID and if the picture exists
  625. if ($this->id && !empty($this->picture)) {
  626. $picture = explode('.', $this->picture);
  627. $extension = $picture[sizeof($picture) - 1];
  628. $picture = 'quiz-'.$questionId.'.'.$extension;
  629. $result = @copy($source_path.'/'.$this->picture, $destination_path.'/'.$picture) ? true : false;
  630. //If copy was correct then add to the database
  631. if ($result) {
  632. $sql = "UPDATE $TBL_QUESTIONS SET picture='".Database::escape_string(
  633. $picture
  634. )."' WHERE c_id = $course_id AND iid='".intval($questionId)."'";
  635. Database::query($sql);
  636. $document_id = FileManager::add_document(
  637. $course_info,
  638. '/images/'.$picture,
  639. 'file',
  640. filesize($destination_path.'/'.$picture),
  641. $picture
  642. );
  643. if ($document_id) {
  644. return api_item_property_update(
  645. $course_info,
  646. TOOL_DOCUMENT,
  647. $document_id,
  648. 'DocumentAdded',
  649. api_get_user_id()
  650. );
  651. }
  652. }
  653. return $result;
  654. }
  655. return false;
  656. }
  657. /**
  658. * Saves the picture coming from POST into a temporary file
  659. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  660. * For example, if we first show a confirmation box.
  661. *
  662. * @author - Olivier Brouckaert
  663. * @param - string $Picture - temporary path of the picture to move
  664. * @param - string $PictureName - Name of the picture
  665. */
  666. function setTmpPicture($Picture, $PictureName)
  667. {
  668. global $picturePath;
  669. $PictureName = explode('.', $PictureName);
  670. $Extension = $PictureName[sizeof($PictureName) - 1];
  671. // saves the picture into a temporary file
  672. @move_uploaded_file($Picture, $picturePath.'/tmp.'.$Extension);
  673. }
  674. /**
  675. Sets the title
  676. */
  677. public function setTitle($title)
  678. {
  679. $this->question = $title;
  680. }
  681. /**
  682. Sets the title
  683. */
  684. public function setExtra($extra)
  685. {
  686. $this->extra = $extra;
  687. }
  688. /**
  689. * Moves the temporary question "tmp" to "quiz-$questionId"
  690. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  691. * For example, if we first show a confirmation box.
  692. *
  693. * @author - Olivier Brouckaert
  694. * @return - boolean - true if moved, otherwise false
  695. */
  696. function getTmpPicture()
  697. {
  698. global $picturePath;
  699. // if the question has got an ID and if the picture exists
  700. if ($this->id) {
  701. if (file_exists($picturePath.'/tmp.jpg')) {
  702. $Extension = 'jpg';
  703. } elseif (file_exists($picturePath.'/tmp.gif')) {
  704. $Extension = 'gif';
  705. } elseif (file_exists($picturePath.'/tmp.png')) {
  706. $Extension = 'png';
  707. }
  708. $this->picture = 'quiz-'.$this->id.'.'.$Extension;
  709. return @rename($picturePath.'/tmp.'.$Extension, $picturePath.'/'.$this->picture) ? true : false;
  710. }
  711. return false;
  712. }
  713. /**
  714. * updates the question in the data base
  715. * if an exercise ID is provided, we add that exercise ID into the exercise list
  716. *
  717. * @author - Olivier Brouckaert
  718. * @param - integer $exerciseId - exercise ID if saving in an exercise
  719. */
  720. function save($exerciseId = 0)
  721. {
  722. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  723. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  724. $id = $this->id;
  725. $question = $this->question;
  726. $description = $this->description;
  727. $weighting = $this->weighting;
  728. $position = $this->position;
  729. $type = $this->type;
  730. $picture = $this->picture;
  731. $level = $this->level;
  732. $extra = $this->extra;
  733. $c_id = $this->course['real_id'];
  734. $category_list = $this->category_list;
  735. // Question already exists
  736. if (!empty($id)) {
  737. $sql = "UPDATE $TBL_QUESTIONS SET
  738. question ='".Database::escape_string($question)."',
  739. description ='".Database::escape_string($description)."',
  740. ponderation ='".Database::escape_string($weighting)."',
  741. position ='".Database::escape_string($position)."',
  742. type ='".Database::escape_string($type)."',
  743. picture ='".Database::escape_string($picture)."',
  744. extra ='".Database::escape_string($extra)."',
  745. level ='".Database::escape_string($level)."',
  746. parent_id = ".$this->parent_id."
  747. WHERE iid = '".Database::escape_string($id)."'";
  748. //WHERE c_id = $c_id AND iid = '".Database::escape_string($id)."'";
  749. Database::query($sql);
  750. $this->saveCategories($category_list);
  751. if (!empty($exerciseId)) {
  752. api_item_property_update($this->course, TOOL_QUIZ, $id, 'QuizQuestionUpdated', api_get_user_id());
  753. if (api_get_setting('search_enabled') == 'true') {
  754. $this->search_engine_edit($exerciseId);
  755. }
  756. }
  757. } else {
  758. // Creates a new question
  759. $sql = "SELECT max(position) FROM $TBL_QUESTIONS as question, $TBL_EXERCICE_QUESTION as test_question
  760. WHERE question.iid = test_question.question_id AND
  761. test_question.exercice_id = '".Database::escape_string($exerciseId)."' AND
  762. question.c_id = $c_id AND
  763. test_question.c_id = $c_id ";
  764. $result = Database::query($sql);
  765. $current_position = Database::result($result, 0, 0);
  766. $this->updatePosition($current_position + 1);
  767. $position = $this->position;
  768. $sql = "INSERT INTO $TBL_QUESTIONS (c_id, question, description, ponderation, position, type, picture, extra, level, parent_id) VALUES ( ".
  769. " $c_id, ".
  770. " '".Database::escape_string($question)."', ".
  771. " '".Database::escape_string($description)."', ".
  772. " '".Database::escape_string($weighting)."', ".
  773. " '".Database::escape_string($position)."', ".
  774. " '".Database::escape_string($type)."', ".
  775. " '".Database::escape_string($picture)."', ".
  776. " '".Database::escape_string($extra)."', ".
  777. " '".Database::escape_string($level)."', ".
  778. " '".$this->parent_id."' ".
  779. " )";
  780. Database::query($sql);
  781. $this->id = Database::insert_id();
  782. api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizQuestionAdded', api_get_user_id());
  783. // If hotspot, create first answer
  784. if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) {
  785. $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
  786. $sql = "INSERT INTO $TBL_ANSWERS (question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type )
  787. VALUES ('".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'square')";
  788. Database::query($sql);
  789. }
  790. if ($type == HOT_SPOT_DELINEATION) {
  791. $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
  792. $sql = "INSERT INTO $TBL_ANSWERS (question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type )
  793. VALUES ('".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'delineation')";
  794. Database::query($sql);
  795. }
  796. if (api_get_setting('search_enabled') == 'true') {
  797. if ($exerciseId != 0) {
  798. $this->search_engine_edit($exerciseId, true);
  799. }
  800. }
  801. }
  802. // if the question is created in an exercise
  803. if ($exerciseId) {
  804. // adds the exercise into the exercise list of this question
  805. $this->addToList($exerciseId, true);
  806. }
  807. }
  808. function search_engine_edit($exerciseId, $addQs = false, $rmQs = false)
  809. {
  810. // update search engine and its values table if enabled
  811. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  812. $course_id = api_get_course_id();
  813. // get search_did
  814. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  815. if ($addQs || $rmQs) {
  816. //there's only one row per question on normal db and one document per question on search engine db
  817. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
  818. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  819. } else {
  820. $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';
  821. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  822. }
  823. $res = Database::query($sql);
  824. if (Database::num_rows($res) > 0 || $addQs) {
  825. require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
  826. require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
  827. $di = new ChamiloIndexer();
  828. if ($addQs) {
  829. $question_exercises = array((int)$exerciseId);
  830. } else {
  831. $question_exercises = array();
  832. }
  833. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  834. $di->connectDb(null, null, $lang);
  835. // retrieve others exercise ids
  836. $se_ref = Database::fetch_array($res);
  837. $se_doc = $di->get_document((int)$se_ref['search_did']);
  838. if ($se_doc !== false) {
  839. if (($se_doc_data = $di->get_document_data($se_doc)) !== false) {
  840. $se_doc_data = unserialize($se_doc_data);
  841. if (isset($se_doc_data[SE_DATA]['type']) && $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION) {
  842. if (isset($se_doc_data[SE_DATA]['exercise_ids']) && is_array(
  843. $se_doc_data[SE_DATA]['exercise_ids']
  844. )
  845. ) {
  846. foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
  847. if (!in_array($old_value, $question_exercises)) {
  848. $question_exercises[] = $old_value;
  849. }
  850. }
  851. }
  852. }
  853. }
  854. }
  855. if ($rmQs) {
  856. while (($key = array_search($exerciseId, $question_exercises)) !== false) {
  857. unset($question_exercises[$key]);
  858. }
  859. }
  860. // build the chunk to index
  861. $ic_slide = new IndexableChunk();
  862. $ic_slide->addValue("title", $this->question);
  863. $ic_slide->addCourseId($course_id);
  864. $ic_slide->addToolId(TOOL_QUIZ);
  865. $xapian_data = array(
  866. SE_COURSE_ID => $course_id,
  867. SE_TOOL_ID => TOOL_QUIZ,
  868. SE_DATA => array(
  869. 'type' => SE_DOCTYPE_EXERCISE_QUESTION,
  870. 'exercise_ids' => $question_exercises,
  871. 'question_id' => (int)$this->id
  872. ),
  873. SE_USER => (int)api_get_user_id(),
  874. );
  875. $ic_slide->xapian_data = serialize($xapian_data);
  876. $ic_slide->addValue("content", $this->description);
  877. //TODO: index answers, see also form validation on question_admin.inc.php
  878. $di->remove_document((int)$se_ref['search_did']);
  879. $di->addChunk($ic_slide);
  880. //index and return search engine document id
  881. if (!empty($question_exercises)) { // if empty there is nothing to index
  882. $did = $di->index();
  883. unset($di);
  884. }
  885. if ($did || $rmQs) {
  886. // save it to db
  887. if ($addQs || $rmQs) {
  888. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=\'%s\'';
  889. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  890. } else {
  891. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\' AND ref_id_second_level=\'%s\'';
  892. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  893. }
  894. Database::query($sql);
  895. if ($rmQs) {
  896. if (!empty($question_exercises)) {
  897. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  898. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  899. $sql = sprintf(
  900. $sql,
  901. $tbl_se_ref,
  902. $course_id,
  903. TOOL_QUIZ,
  904. array_shift($question_exercises),
  905. $this->id,
  906. $did
  907. );
  908. Database::query($sql);
  909. }
  910. } else {
  911. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  912. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  913. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
  914. Database::query($sql);
  915. }
  916. }
  917. }
  918. }
  919. }
  920. /**
  921. * adds an exercise into the exercise list
  922. *
  923. * @author - Olivier Brouckaert
  924. * @param - integer $exerciseId - exercise ID
  925. * @param - boolean $fromSave - comming from $this->save() or not
  926. */
  927. function addToList($exerciseId, $fromSave = false)
  928. {
  929. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  930. $id = $this->id;
  931. // checks if the exercise ID is not in the list
  932. if (!in_array($exerciseId, $this->exerciseList)) {
  933. $this->exerciseList[] = $exerciseId;
  934. $new_exercise = new Exercise();
  935. $new_exercise->read($exerciseId);
  936. $count = $new_exercise->selectNbrQuestions();
  937. $count++;
  938. $sql = "INSERT INTO $TBL_EXERCICE_QUESTION (c_id, question_id, exercice_id, question_order) VALUES
  939. ({$this->course['real_id']}, '".Database::escape_string($id)."','".Database::escape_string(
  940. $exerciseId
  941. )."', '$count' )";
  942. Database::query($sql);
  943. // we do not want to reindex if we had just saved adnd indexed the question
  944. if (!$fromSave) {
  945. $this->search_engine_edit($exerciseId, true);
  946. }
  947. }
  948. }
  949. /**
  950. * removes an exercise from the exercise list
  951. *
  952. * @author - Olivier Brouckaert
  953. * @param - integer $exerciseId - exercise ID
  954. * @return - boolean - true if removed, otherwise false
  955. */
  956. function removeFromList($exerciseId)
  957. {
  958. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  959. $id = $this->id;
  960. // searches the position of the exercise ID in the list
  961. $pos = array_search($exerciseId, $this->exerciseList);
  962. $course_id = api_get_course_int_id();
  963. // exercise not found
  964. if ($pos === false) {
  965. return false;
  966. } else {
  967. // deletes the position in the array containing the wanted exercise ID
  968. unset($this->exerciseList[$pos]);
  969. //update order of other elements
  970. $sql = "SELECT question_order FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id='".Database::escape_string(
  971. $id
  972. )."' AND exercice_id='".Database::escape_string($exerciseId)."'";
  973. $res = Database::query($sql);
  974. if (Database::num_rows($res) > 0) {
  975. $row = Database::fetch_array($res);
  976. if (!empty($row['question_order'])) {
  977. $sql = "UPDATE $TBL_EXERCICE_QUESTION SET question_order = question_order-1
  978. WHERE c_id = $course_id AND exercice_id='".Database::escape_string(
  979. $exerciseId
  980. )."' AND question_order > ".$row['question_order'];
  981. $res = Database::query($sql);
  982. }
  983. }
  984. $sql = "DELETE FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id='".Database::escape_string(
  985. $id
  986. )."' AND exercice_id='".Database::escape_string($exerciseId)."'";
  987. Database::query($sql);
  988. return true;
  989. }
  990. }
  991. /**
  992. * Deletes a question from the database
  993. * the parameter tells if the question is removed from all exercises (value = 0),
  994. * or just from one exercise (value = exercise ID)
  995. *
  996. * @author - Olivier Brouckaert
  997. * @param - integer $deleteFromEx - exercise ID if the question is only removed from one exercise
  998. */
  999. function delete($deleteFromEx = 0)
  1000. {
  1001. $course_id = api_get_course_int_id();
  1002. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1003. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1004. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  1005. $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  1006. $id = $this->id;
  1007. if ($this->type == MEDIA_QUESTION) {
  1008. // Removing media for attached questions
  1009. $sql = "UPDATE $TBL_QUESTIONS SET parent_id = '' WHERE parent_id = $id";
  1010. Database::query($sql);
  1011. $sql = "DELETE FROM $TBL_QUESTIONS WHERE c_id = $course_id AND iid='".Database::escape_string($id)."'";
  1012. Database::query($sql);
  1013. return true;
  1014. }
  1015. // if the question must be removed from all exercises
  1016. if (!$deleteFromEx) {
  1017. //update the question_order of each question to avoid inconsistencies
  1018. $sql = "SELECT exercice_id, question_order FROM $TBL_EXERCICE_QUESTION
  1019. WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."'";
  1020. $res = Database::query($sql);
  1021. if (Database::num_rows($res) > 0) {
  1022. while ($row = Database::fetch_array($res)) {
  1023. if (!empty($row['question_order'])) {
  1024. $sql = "UPDATE $TBL_EXERCICE_QUESTION
  1025. SET question_order = question_order - 1
  1026. WHERE c_id = $course_id AND
  1027. exercice_id='".Database::escape_string($row['exercice_id'])."' AND
  1028. question_order > ".$row['question_order'];
  1029. Database::query($sql);
  1030. }
  1031. }
  1032. }
  1033. $sql = "DELETE FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."'";
  1034. Database::query($sql);
  1035. $sql = "DELETE FROM $TBL_QUESTIONS WHERE c_id = $course_id AND iid='".Database::escape_string($id)."'";
  1036. Database::query($sql);
  1037. $sql = "DELETE FROM $TBL_REPONSES WHERE question_id='".Database::escape_string($id)."'";
  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
  1041. WHERE c_id = $course_id AND question_id='".Database::escape_string($id)."' AND c_id=".api_get_course_int_id();
  1042. Database::query($sql);
  1043. api_item_property_update($this->course, TOOL_QUIZ, $id, 'QuizQuestionDeleted', api_get_user_id());
  1044. $this->removePicture();
  1045. // resets the object
  1046. $this->Question();
  1047. } else {
  1048. // just removes the exercise from the list
  1049. $this->removeFromList($deleteFromEx);
  1050. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1051. // disassociate question with this exercise
  1052. $this->search_engine_edit($deleteFromEx, false, true);
  1053. }
  1054. api_item_property_update($this->course, TOOL_QUIZ, $id, 'QuizQuestionDeleted', api_get_user_id());
  1055. }
  1056. }
  1057. /**
  1058. * Duplicates the question
  1059. *
  1060. * @author Olivier Brouckaert
  1061. * @param array Course info of the destination course
  1062. * @return int ID of the new question
  1063. */
  1064. function duplicate($course_info = null)
  1065. {
  1066. if (empty($course_info)) {
  1067. $course_info = $this->course;
  1068. } else {
  1069. $course_info = $course_info;
  1070. }
  1071. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1072. $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1073. $question = $this->question;
  1074. $description = $this->description;
  1075. $weighting = $this->weighting;
  1076. $position = $this->position;
  1077. $type = $this->type;
  1078. $level = intval($this->level);
  1079. $extra = $this->extra;
  1080. //Using the same method used in the course copy to transform URLs
  1081. if ($this->course['id'] != $course_info['id']) {
  1082. $description = DocumentManager::replace_urls_inside_content_html_from_copy_course(
  1083. $description,
  1084. $this->course['id'],
  1085. $course_info['id']
  1086. );
  1087. $question = DocumentManager::replace_urls_inside_content_html_from_copy_course(
  1088. $question,
  1089. $this->course['id'],
  1090. $course_info['id']
  1091. );
  1092. }
  1093. $course_id = $course_info['real_id'];
  1094. //Read the source options
  1095. $options = self::readQuestionOption($this->id, $this->course['real_id']);
  1096. //Inserting in the new course db / or the same course db
  1097. $params = array(
  1098. 'c_id' => $course_id,
  1099. 'question' => $question,
  1100. 'description' => $description,
  1101. 'ponderation' => $this->weighting,
  1102. 'position' => $this->position,
  1103. 'type' => $this->type,
  1104. 'level' => $this->level,
  1105. 'extra' => $this->extra,
  1106. 'parent_id' => $this->parent_id,
  1107. );
  1108. $new_question_id = Database::insert($TBL_QUESTIONS, $params);
  1109. if (!empty($options)) {
  1110. //Saving the quiz_options
  1111. foreach ($options as $item) {
  1112. $item['question_id'] = $new_question_id;
  1113. $item['c_id'] = $course_id;
  1114. unset($item['iid']);
  1115. Database::insert($TBL_QUESTION_OPTIONS, $item);
  1116. }
  1117. }
  1118. $this->duplicate_category_question($new_question_id, $course_id);
  1119. // Duplicates the picture of the hotspot
  1120. $this->exportPicture($new_question_id, $course_info);
  1121. return $new_question_id;
  1122. }
  1123. function get_categories_from_question()
  1124. {
  1125. return Testcategory::getCategoryForQuestion($this->id);
  1126. }
  1127. function duplicate_category_question($question_id, $course_id)
  1128. {
  1129. $question = Question::read($question_id, $course_id);
  1130. $categories = $this->get_categories_from_question();
  1131. if (!empty($categories)) {
  1132. $question->saveCategories($categories);
  1133. }
  1134. }
  1135. function get_question_type_name()
  1136. {
  1137. $key = self::$questionTypes[$this->type];
  1138. return get_lang($key[1]);
  1139. }
  1140. static function get_question_type($type)
  1141. {
  1142. if ($type == ORAL_EXPRESSION && api_get_setting('enable_nanogong') != 'true') {
  1143. return null;
  1144. }
  1145. return self::$questionTypes[$type];
  1146. }
  1147. static function get_question_type_list()
  1148. {
  1149. if (api_get_setting('enable_nanogong') != 'true') {
  1150. self::$questionTypes[ORAL_EXPRESSION] = null;
  1151. unset(self::$questionTypes[ORAL_EXPRESSION]);
  1152. }
  1153. return self::$questionTypes;
  1154. }
  1155. /**
  1156. * Returns an instance of the class corresponding to the type
  1157. * @param integer $type the type of the question
  1158. * @return an instance of a Question subclass (or of Questionc class by default)
  1159. */
  1160. static function getInstance($type, Exercise $exercise = null)
  1161. {
  1162. if (!is_null($type)) {
  1163. list($file_name, $class_name) = self::get_question_type($type);
  1164. if (!empty($file_name)) {
  1165. include_once $file_name;
  1166. if (class_exists($class_name)) {
  1167. $obj = new $class_name();
  1168. $obj->exercise = $exercise;
  1169. return $obj;
  1170. } else {
  1171. echo 'Can\'t instanciate class '.$class_name.' of type '.$type;
  1172. }
  1173. }
  1174. }
  1175. return null;
  1176. }
  1177. /**
  1178. * Creates the form to create / edit a question
  1179. * A subclass can redifine this function to add fields...
  1180. *
  1181. * @param FormValidator $form the formvalidator instance (by reference)
  1182. */
  1183. public function createForm(&$form, $fck_config = 0)
  1184. {
  1185. $url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?1=1';
  1186. $js = null;
  1187. if ($this->type != MEDIA_QUESTION) {
  1188. $js = '<script>
  1189. function check() {
  1190. $("#category_id option:selected").each(function() {
  1191. var id = $(this).val();
  1192. var name = $(this).text();
  1193. if (id != "" ) {
  1194. $.ajax({
  1195. async: false,
  1196. url: "'.$url.'&a=exercise_category_exists",
  1197. data: "id="+id,
  1198. success: function(return_value) {
  1199. if (return_value == 0 ) {
  1200. alert("'.get_lang('CategoryDoesNotExists').'");
  1201. //Deleting select option tag
  1202. $("#parent_id").find("option").remove();
  1203. $(".holder li").each(function () {
  1204. if ($(this).attr("rel") == id) {
  1205. $(this).remove();
  1206. }
  1207. });
  1208. }
  1209. },
  1210. });
  1211. }
  1212. });
  1213. }
  1214. $(function() {
  1215. $("#category_id").fcbkcomplete({
  1216. json_url: "'.$url.'&a=search_category_parent&type=all&",
  1217. maxitems: 20,
  1218. addontab: false,
  1219. input_min_size: 1,
  1220. cache: false,
  1221. complete_text:"'.get_lang('StartToType').'",
  1222. firstselected: false,
  1223. onselect: check,
  1224. filter_selected: true,
  1225. newel: true
  1226. });
  1227. });
  1228. </script>';
  1229. }
  1230. $js .= '<script>
  1231. // hack to hide http://cksource.com/forums/viewtopic.php?f=6&t=8700
  1232. function FCKeditor_OnComplete( editorInstance ) {
  1233. if (document.getElementById ( \'HiddenFCK\' + editorInstance.Name )) {
  1234. HideFCKEditorByInstanceName (editorInstance.Name);
  1235. }
  1236. }
  1237. function HideFCKEditorByInstanceName ( editorInstanceName ) {
  1238. if (document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className == "HideFCKEditor" ) {
  1239. document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className = "media";
  1240. }
  1241. }
  1242. function show_media(){
  1243. var my_display = document.getElementById(\'HiddenFCKquestionDescription\').style.display;
  1244. if (my_display== \'none\' || my_display == \'\') {
  1245. document.getElementById(\'HiddenFCKquestionDescription\').style.display = \'block\';
  1246. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;'.Display::return_icon('looknfeelna.png').'&nbsp;'.get_lang('EnrichQuestion').'\';
  1247. } else {
  1248. document.getElementById(\'HiddenFCKquestionDescription\').style.display = \'none\';
  1249. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;'.Display::return_icon('looknfeel.png').'&nbsp;'.get_lang('EnrichQuestion').'\';
  1250. }
  1251. }
  1252. // hub 13-12-2010
  1253. function visiblerDevisibler(in_id) {
  1254. if (document.getElementById(in_id)) {
  1255. if (document.getElementById(in_id).style.display == "none") {
  1256. document.getElementById(in_id).style.display = "block";
  1257. if (document.getElementById(in_id+"Img")) {
  1258. document.getElementById(in_id+"Img").html = "'.addslashes(Display::return_icon('div_hide.gif')).'";
  1259. }
  1260. } else {
  1261. document.getElementById(in_id).style.display = "none";
  1262. if (document.getElementById(in_id+"Img")) {
  1263. document.getElementById(in_id+"Img").html = "dsdsds'.addslashes(Display::return_icon('div_show.gif')).'";
  1264. }
  1265. }
  1266. }
  1267. }
  1268. </script>';
  1269. $form->addElement('html', $js);
  1270. // question name
  1271. $form->addElement('text', 'questionName', get_lang('Question'), array('class' => 'span6'));
  1272. $form->addRule('questionName', get_lang('GiveQuestion'), 'required');
  1273. // default content
  1274. $isContent = isset($_REQUEST['isContent']) ? intval($_REQUEST['isContent']) : null;
  1275. // Question type
  1276. $answerType = isset($_REQUEST['answerType']) ? intval($_REQUEST['answerType']) : $this->selectType();
  1277. $form->addElement('hidden', 'answerType', $answerType);
  1278. // html editor
  1279. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  1280. if (is_array($fck_config)) {
  1281. $editor_config = array_merge($editor_config, $fck_config);
  1282. }
  1283. if (!api_is_allowed_to_edit(null, true)) {
  1284. $editor_config['UserStatus'] = 'student';
  1285. }
  1286. if ($this->exercise->fastExerciseEdition == false) {
  1287. $form->addElement(
  1288. 'advanced_settings',
  1289. '<a href="javascript://" onclick=" return show_media()"><span id="media_icon">
  1290. '.Display::return_icon('looknfeel.png').'&nbsp;'.get_lang('EnrichQuestion').'</span></a>
  1291. '
  1292. );
  1293. $form->addElement('html', '<div class="HideFCKEditor" id="HiddenFCKquestionDescription" >');
  1294. }
  1295. $form->add_html_editor('questionDescription', get_lang('QuestionDescription'), false, false, $editor_config);
  1296. if ($this->exercise->fastExerciseEdition == false) {
  1297. $form->addElement('html', '</div>');
  1298. }
  1299. // hidden values
  1300. $my_id = isset($_REQUEST['myid']) ? intval($_REQUEST['myid']) : null;
  1301. $form->addElement('hidden', 'myid', $my_id);
  1302. if ($this->type != MEDIA_QUESTION) {
  1303. if ($this->exercise->fastExerciseEdition == false) {
  1304. // Advanced parameters
  1305. $form->addElement('advanced_settings', '<a class="btn btn-show advanced_parameters" id="advanced_params" href="javascript://">'.get_lang('AdvancedParameters').'</a>');
  1306. $form->addElement('html', '<div id="advanced_params_options" style="display:none;">');
  1307. }
  1308. $select_level = Question::get_default_levels();
  1309. $form->addElement('select', 'questionLevel', get_lang('Difficulty'), $select_level);
  1310. $categoryJS = null;
  1311. if (!empty($this->category_list)) {
  1312. $trigger = '';
  1313. foreach ($this->category_list as $category_id) {
  1314. if (!empty($category_id)) {
  1315. $cat = new Testcategory($category_id);
  1316. if ($cat->id) {
  1317. $trigger .= '$("#category_id").trigger("addItem",[{"title": "'.$cat->parent_path.'", "value": "'.$cat->id.'"}]);';
  1318. }
  1319. }
  1320. }
  1321. $categoryJS .= '<script>$(function() { '.$trigger.' });</script>';
  1322. }
  1323. $form->addElement('html', $categoryJS);
  1324. $form->addElement(
  1325. 'select',
  1326. 'questionCategory',
  1327. get_lang('Category'),
  1328. array(),
  1329. array('id' => 'category_id')
  1330. );
  1331. // Categories
  1332. //$tabCat = Testcategory::getCategoriesIdAndName();
  1333. //$form->addElement('select', 'questionCategory', get_lang('Category'), $tabCat);
  1334. //Medias
  1335. $course_medias = Question::prepare_course_media_select(api_get_course_int_id());
  1336. $form->addElement('select', 'parent_id', get_lang('AttachToMedia'), $course_medias);
  1337. // Inject question extra fields!
  1338. $extraFields = new ExtraField('question');
  1339. $extraFields->add_elements($form, $this->id);
  1340. if ($this->exercise->fastExerciseEdition == false) {
  1341. $form->addElement('html', '</div>');
  1342. }
  1343. }
  1344. // @todo why we need this condition??
  1345. if ($this->setDefaultQuestionValues) {
  1346. switch ($answerType) {
  1347. case 1:
  1348. $this->question = get_lang('DefaultUniqueQuestion');
  1349. break;
  1350. case 2:
  1351. $this->question = get_lang('DefaultMultipleQuestion');
  1352. break;
  1353. case 3:
  1354. $this->question = get_lang('DefaultFillBlankQuestion');
  1355. break;
  1356. case 4:
  1357. $this->question = get_lang('DefaultMathingQuestion');
  1358. break;
  1359. case 5:
  1360. $this->question = get_lang('DefaultOpenQuestion');
  1361. break;
  1362. case 9:
  1363. $this->question = get_lang('DefaultMultipleQuestion');
  1364. break;
  1365. }
  1366. }
  1367. // default values
  1368. $defaults = array();
  1369. $defaults['questionName'] = $this->question;
  1370. $defaults['questionDescription'] = $this->description;
  1371. $defaults['questionLevel'] = $this->level;
  1372. $defaults['questionCategory'] = $this->category_list;
  1373. $defaults['parent_id'] = $this->parent_id;
  1374. //Came from he question pool
  1375. if (isset($_GET['fromExercise'])) {
  1376. $form->setDefaults($defaults);
  1377. }
  1378. if (!empty($_REQUEST['myid'])) {
  1379. $form->setDefaults($defaults);
  1380. } else {
  1381. if ($isContent == 1) {
  1382. $form->setDefaults($defaults);
  1383. }
  1384. }
  1385. if ($this->setDefaultValues) {
  1386. $form->setDefaults($defaults);
  1387. }
  1388. }
  1389. /**
  1390. * function which process the creation of questions
  1391. * @param FormValidator $form the formvalidator instance
  1392. * @param Exercise $objExercise the Exercise instance
  1393. */
  1394. function processCreation($form, $objExercise = null)
  1395. {
  1396. $this->updateParentId($form->getSubmitValue('parent_id'));
  1397. $this->updateTitle($form->getSubmitValue('questionName'));
  1398. $this->updateDescription($form->getSubmitValue('questionDescription'));
  1399. $this->updateLevel($form->getSubmitValue('questionLevel'));
  1400. $this->updateCategory($form->getSubmitValue('questionCategory'));
  1401. // Save normal question if NOT media
  1402. if ($this->type != MEDIA_QUESTION) {
  1403. $this->save($objExercise->id);
  1404. $field_value = new ExtraFieldValue('question');
  1405. $params = $form->exportValues();
  1406. $params['question_id'] = $this->id;
  1407. $field_value->save_field_values($params);
  1408. if ($objExercise) {
  1409. // modify the exercise
  1410. $objExercise->addToList($this->id);
  1411. $objExercise->update_question_positions();
  1412. }
  1413. }
  1414. }
  1415. /**
  1416. * abstract function which creates the form to create / edit the answers of the question
  1417. * @param the formvalidator instance
  1418. */
  1419. abstract function createAnswersForm($form);
  1420. /**
  1421. * abstract function which process the creation of answers
  1422. * @param the formvalidator instance
  1423. */
  1424. abstract function processAnswersCreation($form);
  1425. /**
  1426. * Displays the menu of question types
  1427. */
  1428. static function display_type_menu($objExercise)
  1429. {
  1430. $feedback_type = $objExercise->feedback_type;
  1431. $exerciseId = $objExercise->id;
  1432. // 1. by default we show all the question types
  1433. $question_type_custom_list = self::get_question_type_list();
  1434. if (!isset($feedback_type)) {
  1435. $feedback_type = 0;
  1436. }
  1437. if ($feedback_type == 1) {
  1438. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  1439. $question_type_custom_list = array(
  1440. UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],
  1441. HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION]
  1442. );
  1443. } else {
  1444. unset($question_type_custom_list[HOT_SPOT_DELINEATION]);
  1445. }
  1446. echo '<div class="actionsbig">';
  1447. echo '<ul class="question_menu">';
  1448. foreach ($question_type_custom_list as $i => $a_type) {
  1449. // include the class of the type
  1450. require_once $a_type[0];
  1451. // get the picture of the type and the langvar which describes it
  1452. $img = $explanation = '';
  1453. eval('$img = '.$a_type[1].'::$typePicture;');
  1454. eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
  1455. echo '<li>';
  1456. echo '<div class="icon_image_content">';
  1457. if ($objExercise->exercise_was_added_in_lp == true) {
  1458. $img = pathinfo($img);
  1459. $img = $img['filename'].'_na.'.$img['extension'];
  1460. echo Display::return_icon($img, $explanation, array(), ICON_SIZE_BIG);
  1461. } else {
  1462. echo '<a href="admin.php?'.api_get_cidreq(
  1463. ).'&newQuestion=yes&answerType='.$i.'&exerciseId='.$exerciseId.'">'.Display::return_icon(
  1464. $img,
  1465. $explanation,
  1466. array(),
  1467. ICON_SIZE_BIG
  1468. ).'</a>';
  1469. }
  1470. echo '</div>';
  1471. echo '</li>';
  1472. }
  1473. echo '<li>';
  1474. echo '<div class="icon_image_content">';
  1475. if ($objExercise->exercise_was_added_in_lp == true) {
  1476. echo Display::return_icon('database_na.png', get_lang('GetExistingQuestion'));
  1477. } else {
  1478. if ($feedback_type == 1) {
  1479. //echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&type=1&fromExercise='.$exerciseId.'">';
  1480. } else {
  1481. //echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&fromExercise='.$exerciseId.'">';
  1482. }
  1483. echo $url = '<a href="'.api_get_path(WEB_PUBLIC_PATH).'courses/'.api_get_course_path().'/'.api_get_session_id().'/exercise/'.$exerciseId.'/question-pool">';
  1484. echo Display::return_icon('database.png', get_lang('GetExistingQuestion'));
  1485. }
  1486. echo '</a>';
  1487. echo '</div></li>';
  1488. echo '</ul>';
  1489. echo '</div>';
  1490. }
  1491. static function saveQuestionOption($question_id, $name, $course_id, $position = 0)
  1492. {
  1493. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1494. $params['question_id'] = intval($question_id);
  1495. $params['name'] = $name;
  1496. $params['position'] = $position;
  1497. $params['c_id'] = $course_id;
  1498. //$result = self::readQuestionOption($question_id, $course_id);
  1499. $last_id = Database::insert($TBL_EXERCICE_QUESTION_OPTION, $params);
  1500. return $last_id;
  1501. }
  1502. static function deleteAllQuestionOptions($question_id, $course_id)
  1503. {
  1504. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1505. Database::delete(
  1506. $TBL_EXERCICE_QUESTION_OPTION,
  1507. array('c_id = ? AND question_id = ?' => array($course_id, $question_id))
  1508. );
  1509. }
  1510. static function updateQuestionOption($id, $params, $course_id)
  1511. {
  1512. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1513. $result = Database::update(
  1514. $TBL_EXERCICE_QUESTION_OPTION,
  1515. $params,
  1516. array('c_id = ? AND id = ?' => array($course_id, $id))
  1517. );
  1518. return $result;
  1519. }
  1520. static function readQuestionOption($question_id, $course_id)
  1521. {
  1522. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1523. $result = Database::select(
  1524. '*',
  1525. $TBL_EXERCICE_QUESTION_OPTION,
  1526. array(
  1527. 'where' => array('c_id = ? AND question_id = ?' => array($course_id, $question_id)),
  1528. 'order' => 'iid ASC'
  1529. )
  1530. );
  1531. if (!empty($result)) {
  1532. $new_result = array();
  1533. foreach ($result as $item) {
  1534. $new_result[$item['iid']] = $item;
  1535. }
  1536. return $new_result;
  1537. }
  1538. return array();
  1539. }
  1540. /**
  1541. * Shows question title an description
  1542. *
  1543. * @param type $feedback_type
  1544. * @param type $counter
  1545. * @param type $score
  1546. *
  1547. * @return string
  1548. */
  1549. function return_header($feedback_type = null, $counter = null, $score = null, $show_media)
  1550. {
  1551. $counterLabel = '';
  1552. if (!empty($counter)) {
  1553. $counterLabel = $counter;
  1554. }
  1555. $score_label = get_lang('Wrong');
  1556. $class = 'error';
  1557. if ($score['pass'] == true) {
  1558. $score_label = get_lang('Correct');
  1559. $class = 'success';
  1560. }
  1561. if ($this->type == FREE_ANSWER || $this->type == ORAL_EXPRESSION) {
  1562. if ($score['revised'] == true) {
  1563. $score_label = get_lang('Revised');
  1564. $class = '';
  1565. } else {
  1566. $score_label = get_lang('NotRevised');
  1567. $class = 'error';
  1568. }
  1569. }
  1570. $question_title = $this->question;
  1571. $header = null;
  1572. // Display question category, if any
  1573. if ($show_media) {
  1574. $header .= $this->show_media_content();
  1575. }
  1576. $header .= Display::page_subheader2($counterLabel.". ".$question_title);
  1577. $header .= Display::div(
  1578. '<div class="rib rib-'.$class.'"><h3>'.$score_label.'</h3></div> <h4>'.$score['result'].' </h4>',
  1579. array('class' => 'ribbon')
  1580. );
  1581. $header .= Display::div($this->description, array('id' => 'question_description'));
  1582. return $header;
  1583. }
  1584. /**
  1585. * Create a question from a set of parameters
  1586. * @param int Quiz ID
  1587. * @param string Question name
  1588. * @param int Maximum result for the question
  1589. * @param int Type of question (see constants at beginning of question.class.php)
  1590. * @param int Question level/category
  1591. */
  1592. public function create_question($quiz_id, $question_name, $max_score = 0, $type = 1, $level = 1)
  1593. {
  1594. $course_id = api_get_course_int_id();
  1595. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1596. $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1597. $quiz_id = intval($quiz_id);
  1598. $max_score = (float)$max_score;
  1599. $type = intval($type);
  1600. $level = intval($level);
  1601. // Get the max position
  1602. $sql = "SELECT max(position) as max_position"
  1603. ." FROM $tbl_quiz_question q INNER JOIN $tbl_quiz_rel_question r"
  1604. ." ON q.iid = r.question_id"
  1605. ." AND exercice_id = $quiz_id AND q.c_id = $course_id AND r.c_id = $course_id";
  1606. $rs_max = Database::query($sql);
  1607. $row_max = Database::fetch_object($rs_max);
  1608. $max_position = $row_max->max_position + 1;
  1609. // Insert the new question
  1610. $sql = "INSERT INTO $tbl_quiz_question (c_id, question, ponderation, position, type, level)
  1611. VALUES ($course_id, '".Database::escape_string(
  1612. $question_name
  1613. )."', '$max_score', $max_position, $type, $level)";
  1614. Database::query($sql);
  1615. // Get the question ID
  1616. $question_id = Database::get_last_insert_id();
  1617. // Get the max question_order
  1618. $sql = "SELECT max(question_order) as max_order "
  1619. ."FROM $tbl_quiz_rel_question WHERE c_id = $course_id AND exercice_id = $quiz_id ";
  1620. $rs_max_order = Database::query($sql);
  1621. $row_max_order = Database::fetch_object($rs_max_order);
  1622. $max_order = $row_max_order->max_order + 1;
  1623. // Attach questions to quiz
  1624. $sql = "INSERT INTO $tbl_quiz_rel_question (c_id, question_id, exercice_id, question_order)"
  1625. ." VALUES($course_id, $question_id, $quiz_id, $max_order)";
  1626. Database::query($sql);
  1627. return $question_id;
  1628. }
  1629. /**
  1630. * return the image filename of the question type
  1631. *
  1632. */
  1633. public function get_type_icon_html()
  1634. {
  1635. $type = $this->selectType();
  1636. // [0]=file to include [1]=type name
  1637. $tabQuestionList = Question::get_question_type_list();
  1638. require_once $tabQuestionList[$type][0];
  1639. eval('$img = '.$tabQuestionList[$type][1].'::$typePicture;');
  1640. eval('$explanation = get_lang('.$tabQuestionList[$type][1].'::$explanationLangVar);');
  1641. return array($img, $explanation);
  1642. }
  1643. /**
  1644. * Get course medias
  1645. * @param int course id
  1646. */
  1647. static function get_course_medias(
  1648. $course_id,
  1649. $start = 0,
  1650. $limit = 100,
  1651. $sidx = "question",
  1652. $sord = "ASC",
  1653. $where_condition = array()
  1654. ) {
  1655. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1656. $default_where = array('c_id = ? AND parent_id = 0 AND type = ?' => array($course_id, MEDIA_QUESTION));
  1657. if (!empty($where_condition)) {
  1658. //$where_condition
  1659. }
  1660. $result = Database::select(
  1661. '*',
  1662. $table_question,
  1663. array(
  1664. 'limit' => " $start, $limit",
  1665. 'where' => $default_where,
  1666. 'order' => "$sidx $sord"
  1667. )
  1668. );
  1669. return $result;
  1670. }
  1671. /**
  1672. * Get count course medias
  1673. * @param int course id
  1674. */
  1675. static function get_count_course_medias($course_id)
  1676. {
  1677. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1678. $result = Database::select(
  1679. 'count(*) as count',
  1680. $table_question,
  1681. array('where' => array('c_id = ? AND parent_id = 0 AND type = ?' => array($course_id, MEDIA_QUESTION))),
  1682. 'first'
  1683. );
  1684. if ($result && isset($result['count'])) {
  1685. return $result['count'];
  1686. }
  1687. return 0;
  1688. }
  1689. static function prepare_course_media_select($course_id)
  1690. {
  1691. $medias = self::get_course_medias($course_id);
  1692. $media_list = array();
  1693. $media_list[0] = get_lang('NoMedia');
  1694. if (!empty($medias)) {
  1695. foreach ($medias as $media) {
  1696. $media_list[$media['iid']] = empty($media['question']) ? get_lang('Untitled') : $media['question'];
  1697. }
  1698. }
  1699. return $media_list;
  1700. }
  1701. static function get_default_levels()
  1702. {
  1703. $select_level = array(
  1704. 1 => 1,
  1705. 2 => 2,
  1706. 3 => 3,
  1707. 4 => 4,
  1708. 5 => 5
  1709. );
  1710. return $select_level;
  1711. }
  1712. function show_media_content()
  1713. {
  1714. $html = null;
  1715. if ($this->parent_id != 0) {
  1716. $parent_question = Question::read($this->parent_id);
  1717. $html = $parent_question->show_media_content();
  1718. } else {
  1719. $html .= Display::page_subheader($this->selectTitle());
  1720. $html .= $this->selectDescription();
  1721. }
  1722. return $html;
  1723. }
  1724. public static function question_type_no_review()
  1725. {
  1726. return array(
  1727. HOT_SPOT,
  1728. HOT_SPOT_ORDER,
  1729. HOT_SPOT_DELINEATION
  1730. );
  1731. }
  1732. public static function getMediaLabels()
  1733. {
  1734. // Shows media questions
  1735. $courseMedias = Question::prepare_course_media_select(api_get_course_int_id());
  1736. $labels = null;
  1737. if (!empty($courseMedias)) {
  1738. $labels .= get_lang('MediaQuestion').' ';
  1739. foreach ($courseMedias as $mediaId => $media) {
  1740. $editLink = '<a href="'.api_get_self().'?'.api_get_cidreq().'&type='.MEDIA_QUESTION.'&myid=1&editQuestion='.$mediaId.'">'.Display::return_icon('edit.png',get_lang('Modify'), array(), ICON_SIZE_SMALL).'</a>';
  1741. $deleteLink = '<a id="delete_'.$mediaId.'" class="opener" href="'.api_get_self().'?'.api_get_cidreq().'&deleteQuestion='.$mediaId.'" >'.Display::return_icon('delete.png',get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
  1742. if (!empty($mediaId)) {
  1743. $labels .= self::getMediaLabel($media).''.$editLink.$deleteLink.' ';
  1744. }
  1745. }
  1746. }
  1747. return $labels;
  1748. }
  1749. /**
  1750. * Get question columns needed for the new question pool page
  1751. * @param int course code
  1752. * @return array
  1753. */
  1754. public static function getQuestionColumns($courseCode = null, $questionFields = array())
  1755. {
  1756. // The order is important you need to check the the $column variable in the model.ajax.php file
  1757. //$columns = array('id', get_lang('Name'), get_lang('Description'));
  1758. $columns = array('id', get_lang('Name'));
  1759. // Column config.
  1760. $columnModel = array(
  1761. array(
  1762. 'name' => 'iid',
  1763. 'index' => 'iid',
  1764. 'width' => '20',
  1765. 'align' => 'left'
  1766. ),
  1767. array(
  1768. 'name' => 'question',
  1769. 'index' => 'question',
  1770. 'width' => '200',
  1771. 'align' => 'left'
  1772. ),
  1773. /* array(
  1774. 'name' => 'description',
  1775. 'index' => 'description',
  1776. 'width' => '100',
  1777. 'align' => 'left',
  1778. 'sortable' => 'false'
  1779. )*/
  1780. );
  1781. // Extra field rules.
  1782. $extraField = new \ExtraField('question');
  1783. $rules = $extraField->getRules($columns, $columnModel);
  1784. // Exercise rules.
  1785. self::getRules($courseCode, $rules, $columns, $columnModel, $questionFields);
  1786. $columns[] = get_lang('Actions');
  1787. $columnModel[] = array(
  1788. 'name' => 'actions',
  1789. 'index' => 'actions',
  1790. 'width' => '30',
  1791. 'align' => 'left',
  1792. 'formatter' => 'action_formatter',
  1793. 'sortable' => 'false'
  1794. );
  1795. foreach ($columnModel as $col) {
  1796. $simple_column_name[] = $col['name'];
  1797. }
  1798. $return_array = array(
  1799. 'columns' => $columns,
  1800. 'column_model' => $columnModel,
  1801. 'rules' => $rules,
  1802. 'simple_column_name' => $simple_column_name
  1803. );
  1804. return $return_array;
  1805. }
  1806. /**
  1807. * Get all questions
  1808. * @param array $options
  1809. * @return array
  1810. */
  1811. public static function getQuestions($categoryId, $exerciseId, $courseId, $options, $get_count = false)
  1812. {
  1813. $questionTable = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1814. $questionPoolFields = array(
  1815. 'question_session_id' => array(
  1816. 'innerjoin' => " INNER JOIN ".Database::get_course_table(TABLE_QUIZ_TEST_QUESTION)." as quiz_rel_question_session ON (quiz_rel_question_session.question_id = s.iid)
  1817. INNER JOIN ".Database::get_course_table(TABLE_QUIZ_TEST)." as quizsession ON (quizsession.iid = quiz_rel_question_session.exercice_id)
  1818. INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)." session ON (session.id = quizsession.session_id)",
  1819. 'where' => 'session_id',
  1820. 'inject_fields' => 'session.name as question_session_id, ',
  1821. ),
  1822. 'question_category_id' => array(
  1823. 'innerjoin' => " INNER JOIN ".Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY)." as quiz_rel_cat ON (quiz_rel_cat.question_id = s.iid)
  1824. INNER JOIN ".Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY)." as cat ON (cat.iid = quiz_rel_cat.category_id)
  1825. ",
  1826. 'where' => 'quiz_rel_cat.category_id',
  1827. 'inject_fields' => 'cat.title as question_category_id, ',
  1828. ),
  1829. 'question_exercise_id' => array(
  1830. 'innerjoin' => " INNER JOIN ".Database::get_course_table(TABLE_QUIZ_TEST_QUESTION)." as quiz_rel_question ON (quiz_rel_question.question_id = s.iid)
  1831. INNER JOIN ".Database::get_course_table(TABLE_QUIZ_TEST)." as quizexercise ON (quizexercise.iid = quiz_rel_question.exercice_id)
  1832. ",
  1833. 'where' => 'quiz_rel_question.exercice_id',
  1834. 'inject_fields' => 'quizexercise.title as question_exercise_id, ',
  1835. ),
  1836. 'question_c_id' => array(
  1837. 'where' => 's.c_id',
  1838. 'innerjoin' => " INNER JOIN ".Database::get_main_table(TABLE_MAIN_COURSE)." as course ON (course.id = s.c_id) ",
  1839. 'inject_fields' => 'course.title as question_c_id, '
  1840. ),
  1841. 'question_question_type' => array(
  1842. 'where' => 's.type ',
  1843. 'inject_fields' => 's.type as question_question_type,'
  1844. ),
  1845. 'question_difficulty' => array(
  1846. 'where' => 's.level',
  1847. 'inject_fields' => 's.level as question_difficulty, '
  1848. )
  1849. );
  1850. $inject_extra_fields = null;
  1851. $inject_joins = null;
  1852. $where = $options['where'];
  1853. $newQuestionPoolField = array();
  1854. if (isset($options['question'])) {
  1855. foreach ($options['question'] as $question) {
  1856. if (isset($questionPoolFields[$question['field']])) {
  1857. $newQuestionPoolField[$question['field']] = $questionPoolFields[$question['field']];
  1858. }
  1859. }
  1860. }
  1861. $inject_question_fields = null;
  1862. $questionPoolFields = $newQuestionPoolField;
  1863. foreach ($questionPoolFields as $field => $option) {
  1864. $where = str_replace($field, $option['where'], $where);
  1865. if (isset($option['innerjoin']) && !empty($option['innerjoin'])) {
  1866. $inject_joins .= $option['innerjoin'];
  1867. }
  1868. if (isset($option['inject_fields']) && !empty($option['inject_fields'])) {
  1869. $inject_question_fields .= $option['inject_fields'];
  1870. }
  1871. }
  1872. $options['where'] = $where;
  1873. $extra_field = new ExtraField('question');
  1874. $conditions = $extra_field->parseConditions($options);
  1875. $inject_joins .= $conditions['inject_joins'];
  1876. $where = $conditions['where'];
  1877. $inject_where = $conditions['inject_where'];
  1878. $inject_extra_fields = $conditions['inject_extra_fields'];
  1879. $order = $conditions['order'];
  1880. $limit = $conditions['limit'];
  1881. if ($get_count == true) {
  1882. $select = " SELECT count(*) as total_rows";
  1883. } else {
  1884. $select = " SELECT s.*, $inject_extra_fields $inject_question_fields 1 ";
  1885. }
  1886. $extraCondition = null;
  1887. if (!empty($categoryId)) {
  1888. $categoryRelQuestionTable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  1889. $extraCondition = " INNER JOIN $categoryRelQuestionTable c ON (s.iid = c.question_id)";
  1890. $categoryId = intval($categoryId);
  1891. $where .= " AND category_id = $categoryId ";
  1892. }
  1893. if (!empty($exerciseId)) {
  1894. $exerciseRelQuestionTable = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1895. $extraCondition .= " INNER JOIN $exerciseRelQuestionTable e ON (s.iid = e.question_id)";
  1896. $exerciseId = intval($exerciseId);
  1897. $where .= " AND exercice_id = $exerciseId ";
  1898. }
  1899. if (!empty($courseId)) {
  1900. $courseId = intval($courseId);
  1901. $where .= " AND s.c_id = $courseId ";
  1902. }
  1903. $query = " $select FROM $questionTable s $inject_joins $extraCondition WHERE 1=1 $where $inject_where $order $limit";
  1904. //echo $query.'<br />';
  1905. $result = Database::query($query);
  1906. $questions = array();
  1907. if (Database::num_rows($result)) {
  1908. $questions = Database::store_result($result, 'ASSOC');
  1909. if ($get_count) {
  1910. return $questions[0]['total_rows'];
  1911. }
  1912. }
  1913. return $questions;
  1914. }
  1915. public static function getMediaLabel($title)
  1916. {
  1917. return Display::label($title, 'warning');
  1918. }
  1919. /**
  1920. * @param $courseCode
  1921. * @param $rules
  1922. * @param $columns
  1923. * @param $column_model
  1924. * @return array
  1925. */
  1926. public static function getRules($courseCode, &$rules, &$columns, &$column_model, $questionFields)
  1927. {
  1928. // sessions
  1929. // course
  1930. // categories
  1931. // exercises
  1932. // difficult
  1933. // type
  1934. if (empty($courseCode)) {
  1935. // Session
  1936. $sessionList = SessionManager::get_sessions_by_general_coach(api_get_user_id());
  1937. $fields = array();
  1938. if (!empty($sessionList)) {
  1939. $new_options = array();
  1940. $new_options[] = "-1:".get_lang('All');
  1941. foreach ($sessionList as $session) {
  1942. $new_options[] = "{$session['id']}:{$session['name']}";
  1943. }
  1944. $string = implode(';', $new_options);
  1945. $fields[] = array(
  1946. 'field_display_text' => get_lang('Session'),
  1947. 'field_variable' => 'session_id',
  1948. 'field_type' => ExtraField::FIELD_TYPE_SELECT,
  1949. 'field_default_value' => null,
  1950. 'field_options' => $string
  1951. );
  1952. }
  1953. // Courses
  1954. $courseList = CourseManager::get_course_list_of_user_as_course_admin(api_get_user_id());
  1955. if (!empty($courseList)) {
  1956. $new_options = array();
  1957. $new_options[] = "-1:".get_lang('All');
  1958. foreach ($courseList as $course) {
  1959. $new_options[] = "{$course['id']}:{$course['title']}";
  1960. }
  1961. $string = implode(';', $new_options);
  1962. $fields[] = array(
  1963. 'field_display_text' => get_lang('Course'),
  1964. 'field_variable' => 'c_id',
  1965. 'field_type' => ExtraField::FIELD_TYPE_SELECT,
  1966. 'field_default_value' => null,
  1967. 'field_options' => $string
  1968. );
  1969. }
  1970. } else {
  1971. $courseList = array(api_get_course_info());
  1972. }
  1973. // Categories
  1974. $string = null;
  1975. if (!empty($courseList)) {
  1976. $new_options = array();
  1977. $new_options[] = "-1:".get_lang('All');
  1978. // Global categories
  1979. // @todo use tree view
  1980. $categories = Testcategory::getCategoriesIdAndName(0);
  1981. if (!empty($categories)) {
  1982. foreach ($categories as $id => $category) {
  1983. if (!empty($id)) {
  1984. $new_options[] = "$id:[Global] - ".$category;
  1985. }
  1986. }
  1987. }
  1988. foreach ($courseList as $course) {
  1989. $categories = Testcategory::getCategoriesIdAndName($course['real_id']);
  1990. if (!empty($categories)) {
  1991. foreach ($categories as $id => $category) {
  1992. if (!empty($id)) {
  1993. $new_options[] = "$id:".$course['title']." - ".$category;
  1994. }
  1995. }
  1996. }
  1997. }
  1998. $string = implode(';', $new_options);
  1999. $fields[] = array(
  2000. 'field_display_text' => get_lang('Category'),
  2001. 'field_variable' => 'category_id',
  2002. 'field_type' => ExtraField::FIELD_TYPE_SELECT,
  2003. 'field_default_value' => null,
  2004. 'field_options' => $string
  2005. );
  2006. }
  2007. $course = api_get_course_int_id();
  2008. $sessionId = api_get_session_id();
  2009. // Exercises
  2010. $exerciseList = ExerciseLib::get_all_exercises_for_course_id($sessionId, $course);
  2011. if (!empty($exerciseList)) {
  2012. $new_options = array();
  2013. $new_options[] = "-1:".get_lang('All');
  2014. $new_options[] = "0:".get_lang('Orphan');
  2015. foreach ($exerciseList as $exercise) {
  2016. $new_options[] = "{$exercise['iid']}:{$exercise['title']}";
  2017. }
  2018. $string = implode(';', $new_options);
  2019. $fields[] = array(
  2020. 'field_display_text' => get_lang('Exercise'),
  2021. 'field_variable' => 'exercise_id',
  2022. 'field_type' => ExtraField::FIELD_TYPE_SELECT,
  2023. 'field_default_value' => null,
  2024. 'field_options' => $string
  2025. );
  2026. }
  2027. // Question type
  2028. $questionList = Question::get_question_type_list();
  2029. if (!empty($questionList)) {
  2030. $new_options = array();
  2031. $new_options[] = "-1:".get_lang('All');
  2032. foreach ($questionList as $key => $question) {
  2033. $new_options[] = "{$key}:".get_lang($question['1']);
  2034. }
  2035. $string = implode(';', $new_options);
  2036. $fields[] = array(
  2037. 'field_display_text' => get_lang('AnswerType'),
  2038. 'field_variable' => 'question_type',
  2039. 'field_type' => ExtraField::FIELD_TYPE_SELECT,
  2040. 'field_default_value' => null,
  2041. 'field_options' => $string
  2042. );
  2043. }
  2044. // Difficult
  2045. $levels = Question::get_default_levels();
  2046. if (!empty($levels)) {
  2047. $new_options = array();
  2048. $new_options[] = "-1:".get_lang('All');
  2049. foreach ($levels as $key => $level) {
  2050. $new_options[] ="{$key}:{$level}";
  2051. }
  2052. $string = implode(';', $new_options);
  2053. $fields[] = array(
  2054. 'field_display_text' => get_lang('Difficulty'),
  2055. 'field_variable' => 'difficulty',
  2056. 'field_type' => ExtraField::FIELD_TYPE_SELECT,
  2057. 'field_default_value' => null,
  2058. 'field_options' => $string
  2059. );
  2060. }
  2061. $questionFieldsKeys = array();
  2062. if (!empty($questionFields)) {
  2063. foreach ($questionFields as $question) {
  2064. $questionFieldsKeys[] = $question['field'];
  2065. }
  2066. }
  2067. if (!empty($fields)) {
  2068. foreach ($fields as $field) {
  2069. if (isset($questionFields) && !empty($questionFields)) {
  2070. if (!in_array('question_'.$field['field_variable'], $questionFieldsKeys)) {
  2071. continue;
  2072. }
  2073. }
  2074. $search_options = array();
  2075. $type = 'text';
  2076. if (in_array($field['field_type'], array(ExtraField::FIELD_TYPE_SELECT, ExtraField::FIELD_TYPE_DOUBLE_SELECT))) {
  2077. $type = 'select';
  2078. $search_options['sopt'] = array('eq', 'ne'); //equal not equal
  2079. //$search_options['sopt'] = array('cn', 'nc'); //contains not contains
  2080. } else {
  2081. $search_options['sopt'] = array('cn', 'nc'); //contains not contains
  2082. }
  2083. $search_options['searchhidden'] = 'true';
  2084. $search_options['defaultValue'] = isset($search_options['field_default_value']) ? $search_options['field_default_value'] : null;
  2085. $search_options['value'] = $field['field_options'];
  2086. $column_model[] = array(
  2087. 'name' => 'question_'.$field['field_variable'],
  2088. 'index' => 'question_'.$field['field_variable'],
  2089. 'width' => '100',
  2090. 'hidden' => 'true',
  2091. 'search' => 'true',
  2092. 'stype' => $type,
  2093. 'searchoptions' => $search_options
  2094. );
  2095. $columns[] = $field['field_display_text'];
  2096. $rules[] = array(
  2097. 'field' => 'question_'.$field['field_variable'],
  2098. 'op' => 'eq'
  2099. );
  2100. }
  2101. }
  2102. return $rules;
  2103. }
  2104. }