TestCategory.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * Class TestCategory
  6. * @author hubert.borderiou
  7. * @author Julio Montoya - several fixes
  8. * @todo rename to ExerciseCategory
  9. */
  10. class TestCategory
  11. {
  12. public $id;
  13. public $name;
  14. public $description;
  15. /**
  16. * Constructor of the class Category
  17. */
  18. public function __construct()
  19. {
  20. }
  21. /**
  22. * return the TestCategory object with id=in_id
  23. * @param int $id
  24. *
  25. * @return TestCategory
  26. */
  27. public function getCategory($id)
  28. {
  29. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  30. $id = intval($id);
  31. $sql = "SELECT * FROM $table
  32. WHERE id = $id AND c_id=".api_get_course_int_id();
  33. $res = Database::query($sql);
  34. if (Database::num_rows($res)) {
  35. $row = Database::fetch_array($res);
  36. $this->id = $row['id'];
  37. $this->name = $row['title'];
  38. $this->description = $row['description'];
  39. return $this;
  40. }
  41. return false;
  42. }
  43. /**
  44. * add TestCategory in the database if name doesn't already exists
  45. */
  46. public function addCategoryInBDD()
  47. {
  48. $table = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  49. $name = Database::escape_string($this->name);
  50. $description = Database::escape_string($this->description);
  51. // check if name already exists
  52. $sql = "SELECT count(*) AS nb FROM $table
  53. WHERE title = '$name' AND c_id=".api_get_course_int_id();
  54. $result = Database::query($sql);
  55. $data_verif = Database::fetch_array($result);
  56. // lets add in BDD if not the same name
  57. if ($data_verif['nb'] <= 0) {
  58. $c_id = api_get_course_int_id();
  59. $params = [
  60. 'c_id' => $c_id,
  61. 'title' => $name,
  62. 'description' => $description
  63. ];
  64. $new_id = Database::insert($table, $params);
  65. if ($new_id) {
  66. $sql = "UPDATE $table SET id = iid WHERE iid = $new_id";
  67. Database::query($sql);
  68. // add test_category in item_property table
  69. $course_id = api_get_course_int_id();
  70. $course_info = api_get_course_info_by_id($course_id);
  71. api_item_property_update(
  72. $course_info,
  73. TOOL_TEST_CATEGORY,
  74. $new_id,
  75. 'TestCategoryAdded',
  76. api_get_user_id()
  77. );
  78. }
  79. return $new_id;
  80. } else {
  81. return false;
  82. }
  83. }
  84. /**
  85. * Removes the category from the database
  86. * if there were question in this category, the link between question and category is removed
  87. */
  88. public function removeCategory($id)
  89. {
  90. $table = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  91. $tbl_question_rel_cat = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  92. $id = intval($id);
  93. $course_id = api_get_course_int_id();
  94. $category = $this->getCategory($id);
  95. if ($category) {
  96. $sql = "DELETE FROM $table
  97. WHERE id= $id AND c_id=".$course_id;
  98. Database::query($sql);
  99. // remove link between question and category
  100. $sql = "DELETE FROM $tbl_question_rel_cat
  101. WHERE category_id = $id AND c_id=".$course_id;
  102. Database::query($sql);
  103. // item_property update
  104. $course_info = api_get_course_info_by_id($course_id);
  105. api_item_property_update(
  106. $course_info,
  107. TOOL_TEST_CATEGORY,
  108. $this->id,
  109. 'TestCategoryDeleted',
  110. api_get_user_id()
  111. );
  112. return true;
  113. }
  114. return false;
  115. }
  116. /**
  117. * Modify category name or description of category with id=in_id
  118. */
  119. public function modifyCategory()
  120. {
  121. $table = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  122. $id = intval($this->id);
  123. $name = Database::escape_string($this->name);
  124. $description = Database::escape_string($this->description);
  125. $cat = $this->getCategory($id);
  126. if ($cat) {
  127. $sql = "UPDATE $table SET
  128. title = '$name',
  129. description = '$description'
  130. WHERE id = $id AND c_id=".api_get_course_int_id();
  131. Database::query($sql);
  132. // item_property update
  133. $course_id = api_get_course_int_id();
  134. $course_info = api_get_course_info_by_id($course_id);
  135. api_item_property_update(
  136. $course_info,
  137. TOOL_TEST_CATEGORY,
  138. $this->id,
  139. 'TestCategoryModified',
  140. api_get_user_id()
  141. );
  142. return true;
  143. }
  144. return false;
  145. }
  146. /**
  147. * Gets the number of question of category id=in_id
  148. */
  149. public function getCategoryQuestionsNumber()
  150. {
  151. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  152. $in_id = intval($this->id);
  153. $sql = "SELECT count(*) AS nb
  154. FROM $table
  155. WHERE category_id=$in_id AND c_id=".api_get_course_int_id();
  156. $res = Database::query($sql);
  157. $row = Database::fetch_array($res);
  158. return $row['nb'];
  159. }
  160. /**
  161. * Return an array of all Category objects in the database
  162. * If in_field=="" Return an array of all category objects in the database
  163. * Otherwise, return an array of all in_field value
  164. * in the database (in_field = id or name or description)
  165. *
  166. * @param string $in_field
  167. * @param int $courseId
  168. * @return array
  169. */
  170. public static function getCategoryListInfo($in_field = '', $courseId = 0)
  171. {
  172. if (empty($courseId)) {
  173. $courseId = api_get_course_int_id();
  174. }
  175. $table = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  176. $in_field = Database::escape_string($in_field);
  177. $categories = array();
  178. if ($in_field == '') {
  179. $sql = "SELECT id FROM $table
  180. WHERE c_id=$courseId ORDER BY title ASC";
  181. $res = Database::query($sql);
  182. while ($row = Database::fetch_array($res)) {
  183. $category = new TestCategory();
  184. $categories[] = $category->getCategory($row['id']);
  185. }
  186. } else {
  187. $sql = "SELECT $in_field FROM $table
  188. WHERE c_id = $courseId
  189. ORDER BY $in_field ASC";
  190. $res = Database::query($sql);
  191. while ($row = Database::fetch_array($res)) {
  192. $categories[] = $row[$in_field];
  193. }
  194. }
  195. return $categories;
  196. }
  197. /**
  198. * Return the TestCategory id for question with question_id = $questionId
  199. * In this version, a question has only 1 TestCategory.
  200. * Return the TestCategory id, 0 if none
  201. * @param int $questionId
  202. * @param int $courseId
  203. *
  204. * @return int
  205. */
  206. public static function getCategoryForQuestion($questionId, $courseId = 0)
  207. {
  208. if (empty($courseId)) {
  209. $courseId = api_get_course_int_id();
  210. }
  211. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  212. $questionId = intval($questionId);
  213. $sql = "SELECT category_id
  214. FROM $table
  215. WHERE question_id = $questionId AND c_id = $courseId";
  216. $res = Database::query($sql);
  217. $result = 0;
  218. if (Database::num_rows($res) > 0) {
  219. $data = Database::fetch_array($res);
  220. $result = $data['category_id'];
  221. }
  222. return $result;
  223. }
  224. /**
  225. * true if question id has a category
  226. *
  227. * @param int $questionId
  228. * @return bool
  229. */
  230. public static function isQuestionHasCategory($questionId)
  231. {
  232. if (TestCategory::getCategoryForQuestion($questionId) > 0) {
  233. return true;
  234. }
  235. return false;
  236. }
  237. /**
  238. Return the category name for question with question_id = $questionId
  239. In this version, a question has only 1 category.
  240. Return the category id, "" if none
  241. */
  242. public static function getCategoryNameForQuestion(
  243. $questionId,
  244. $courseId = 0
  245. ) {
  246. if (empty($courseId)) {
  247. $courseId = api_get_course_int_id();
  248. }
  249. $categoryId = TestCategory::getCategoryForQuestion($questionId, $courseId);
  250. $result = '';
  251. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  252. $categoryId = intval($categoryId);
  253. $sql = "SELECT title FROM $table
  254. WHERE id = $categoryId AND c_id = $courseId";
  255. $res = Database::query($sql);
  256. $data = Database::fetch_array($res);
  257. if (Database::num_rows($res) > 0) {
  258. $result = $data['title'];
  259. }
  260. return $result;
  261. }
  262. /**
  263. * Return the list of differents categories ID for a test in the current course
  264. * input : test_id
  265. * return : array of category id (integer)
  266. * hubert.borderiou 07-04-2011
  267. * @param int $exerciseId
  268. *
  269. * @return array
  270. */
  271. public static function getListOfCategoriesIDForTest($exerciseId)
  272. {
  273. // parcourir les questions d'un test, recup les categories uniques dans un tableau
  274. $exercise = new Exercise();
  275. $exercise->read($exerciseId, false);
  276. $categoriesInExercise = $exercise->getQuestionWithCategories();
  277. // the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???
  278. $categories = array();
  279. if (!empty($categoriesInExercise)) {
  280. foreach ($categoriesInExercise as $category) {
  281. $categories[$category['id']] = $category;
  282. }
  283. }
  284. return $categories;
  285. }
  286. /**
  287. * @param Exercise $exercise_obj
  288. * @return array
  289. */
  290. public static function getListOfCategoriesIDForTestObject(Exercise $exercise_obj)
  291. {
  292. // parcourir les questions d'un test, recup les categories uniques dans un tableau
  293. $categories_in_exercise = array();
  294. // $question_list = $exercise_obj->getQuestionList();
  295. $question_list = $exercise_obj->getQuestionOrderedListByName();
  296. // the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???
  297. foreach ($question_list as $questionInfo) {
  298. $question_id = $questionInfo['question_id'];
  299. $category_list = self::getCategoryForQuestion($question_id);
  300. if (is_numeric($category_list)) {
  301. $category_list = array($category_list);
  302. }
  303. if (!empty($category_list)) {
  304. $categories_in_exercise = array_merge($categories_in_exercise, $category_list);
  305. }
  306. }
  307. if (!empty($categories_in_exercise)) {
  308. $categories_in_exercise = array_unique(array_filter($categories_in_exercise));
  309. }
  310. return $categories_in_exercise;
  311. }
  312. /**
  313. * Return the list of differents categories NAME for a test
  314. * @param int exercise id
  315. * @param bool
  316. * @return integer of string
  317. *
  318. * @author function rewrote by jmontoya
  319. */
  320. public static function getListOfCategoriesNameForTest($exercise_id, $grouped_by_category = true)
  321. {
  322. $result = array();
  323. $categories = self::getListOfCategoriesIDForTest($exercise_id, $grouped_by_category);
  324. foreach ($categories as $catInfo) {
  325. $categoryId = $catInfo['id'];
  326. if (!empty($categoryId)) {
  327. $result[$categoryId] = array(
  328. 'title' => $catInfo['title'],
  329. //'parent_id' => $catInfo['parent_id'],
  330. 'parent_id' => '',
  331. 'c_id' => $catInfo['c_id']
  332. );
  333. }
  334. }
  335. return $result;
  336. }
  337. /**
  338. * @param Exercise $exercise_obj
  339. * @return array
  340. */
  341. public static function getListOfCategoriesForTest(Exercise $exercise_obj)
  342. {
  343. $result = array();
  344. $categories = self::getListOfCategoriesIDForTestObject($exercise_obj);
  345. foreach ($categories as $cat_id) {
  346. $cat = new TestCategory();
  347. $cat = (array)$cat->getCategory($cat_id);
  348. $cat['iid'] = $cat['id'];
  349. $cat['title'] = $cat['name'];
  350. $result[$cat['id']] = $cat;
  351. }
  352. return $result;
  353. }
  354. /**
  355. * return the number of differents categories for a test
  356. * input : test_id
  357. * return : integer
  358. * hubert.borderiou 07-04-2011
  359. */
  360. public static function getNumberOfCategoriesForTest($id)
  361. {
  362. return count(TestCategory::getListOfCategoriesIDForTest($id));
  363. }
  364. /**
  365. * return the number of question of a category id in a test
  366. * @param int $exerciseId
  367. * @param int $categoryId
  368. *
  369. * @return integer
  370. *
  371. * @author hubert.borderiou 07-04-2011
  372. */
  373. public static function getNumberOfQuestionsInCategoryForTest($exerciseId, $categoryId)
  374. {
  375. $nbCatResult = 0;
  376. $quiz = new Exercise();
  377. $quiz->read($exerciseId);
  378. $questionList = $quiz->selectQuestionList();
  379. // the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ? ? ?
  380. for ($i=1; $i <= count($questionList); $i++) {
  381. if (TestCategory::getCategoryForQuestion($questionList[$i]) == $categoryId) {
  382. $nbCatResult++;
  383. }
  384. }
  385. return $nbCatResult;
  386. }
  387. /**
  388. * return the number of question for a test using random by category
  389. * input : test_id, number of random question (min 1)
  390. * hubert.borderiou 07-04-2011
  391. * question without categories are not counted
  392. */
  393. public static function getNumberOfQuestionRandomByCategory($exerciseId, $in_nbrandom)
  394. {
  395. $nbquestionresult = 0;
  396. $categories = TestCategory::getListOfCategoriesIDForTest($exerciseId);
  397. foreach ($categories as $category) {
  398. if (empty($category['id'])) {
  399. continue;
  400. }
  401. $nbQuestionInThisCat = TestCategory::getNumberOfQuestionsInCategoryForTest($exerciseId, $category['id']);
  402. if ($nbQuestionInThisCat > $in_nbrandom) {
  403. $nbquestionresult += $in_nbrandom;
  404. } else {
  405. $nbquestionresult += $nbQuestionInThisCat;
  406. }
  407. }
  408. return $nbquestionresult;
  409. }
  410. /**
  411. * Return an array (id=>name)
  412. * tabresult[0] = get_lang('NoCategory');
  413. *
  414. * @param int $courseId
  415. *
  416. * @return array
  417. *
  418. */
  419. public static function getCategoriesIdAndName($courseId = 0)
  420. {
  421. if (empty($courseId)) {
  422. $courseId = api_get_course_int_id();
  423. }
  424. $categories = TestCategory::getCategoryListInfo('', $courseId);
  425. $tabresult = array('0' => get_lang('NoCategorySelected'));
  426. for ($i=0; $i < count($categories); $i++) {
  427. $tabresult[$categories[$i]->id] = $categories[$i]->name;
  428. }
  429. return $tabresult;
  430. }
  431. /**
  432. * Returns an array of question ids for each category
  433. * $categories[1][30] = 10, array with category id = 1 and question_id = 10
  434. * A question has "n" categories
  435. * @param int exercise
  436. * @param array $check_in_question_list
  437. * @param array $categoriesAddedInExercise
  438. *
  439. * @param int $exerciseId
  440. * @return array
  441. */
  442. static function getQuestionsByCat(
  443. $exerciseId,
  444. $check_in_question_list = array(),
  445. $categoriesAddedInExercise = array()
  446. ) {
  447. $tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
  448. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  449. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  450. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  451. $exerciseId = intval($exerciseId);
  452. $courseId = api_get_course_int_id();
  453. $sql = "SELECT DISTINCT qrc.question_id, qrc.category_id
  454. FROM $TBL_QUESTION_REL_CATEGORY qrc
  455. INNER JOIN $TBL_EXERCICE_QUESTION eq
  456. ON (eq.question_id = qrc.question_id)
  457. INNER JOIN $categoryTable c
  458. ON (c.id = qrc.category_id)
  459. INNER JOIN $tableQuestion q
  460. ON (q.id = qrc.question_id )
  461. WHERE
  462. exercice_id = $exerciseId AND
  463. qrc.c_id = $courseId
  464. ";
  465. $res = Database::query($sql);
  466. $categories = array();
  467. while ($data = Database::fetch_array($res)) {
  468. if (!empty($check_in_question_list)) {
  469. if (!in_array($data['question_id'], $check_in_question_list)) {
  470. continue;
  471. }
  472. }
  473. if (!isset($categories[$data['category_id']]) ||
  474. !is_array($categories[$data['category_id']])
  475. ) {
  476. $categories[$data['category_id']] = array();
  477. }
  478. $categories[$data['category_id']][] = $data['question_id'];
  479. }
  480. if (!empty($categoriesAddedInExercise)) {
  481. $newCategoryList = array();
  482. foreach ($categoriesAddedInExercise as $category) {
  483. $categoryId = $category['category_id'];
  484. if (isset($categories[$categoryId])) {
  485. $newCategoryList[$categoryId] = $categories[$categoryId];
  486. }
  487. }
  488. $checkQuestionsWithNoCategory = false;
  489. foreach ($categoriesAddedInExercise as $category) {
  490. if (empty($category['category_id'])) {
  491. // Check
  492. $checkQuestionsWithNoCategory = true;
  493. break;
  494. }
  495. }
  496. // Select questions that don't have any category related
  497. if ($checkQuestionsWithNoCategory) {
  498. $originalQuestionList = $check_in_question_list;
  499. foreach ($originalQuestionList as $questionId) {
  500. $categoriesFlatten = array_flatten($categories);
  501. if (!in_array($questionId, $categoriesFlatten)) {
  502. $newCategoryList[0][] = $questionId;
  503. }
  504. }
  505. }
  506. $categories = $newCategoryList;
  507. }
  508. return $categories;
  509. }
  510. /**
  511. * return a tab of $in_number random elements of $in_tab
  512. */
  513. public static function getNElementsFromArray($in_tab, $in_number)
  514. {
  515. $list = $in_tab;
  516. shuffle($list);
  517. if ($in_number < count($list)) {
  518. $list = array_slice($list, 0, $in_number);
  519. }
  520. return $list;
  521. }
  522. /**
  523. * @param int $questionId
  524. * @param int $in_display_category_name
  525. */
  526. public static function displayCategoryAndTitle($questionId, $in_display_category_name = 1)
  527. {
  528. echo self::returnCategoryAndTitle($questionId, $in_display_category_name);
  529. }
  530. /**
  531. * @param int $questionId
  532. * @param int $in_display_category_name
  533. * @return null|string
  534. */
  535. public static function returnCategoryAndTitle($questionId, $in_display_category_name = 1)
  536. {
  537. $is_student = !(api_is_allowed_to_edit(null,true) || api_is_session_admin());
  538. // @todo fix $_SESSION['objExercise']
  539. $objExercise = Session::read('objExercise');
  540. if (!empty($objExercise)) {
  541. $in_display_category_name = $objExercise->display_category_name;
  542. }
  543. $content = null;
  544. if (TestCategory::getCategoryNameForQuestion($questionId) != '' && ($in_display_category_name == 1 || !$is_student)) {
  545. $content .= '<div class="page-header">';
  546. $content .= '<h4>'.get_lang('Category').": ".TestCategory::getCategoryNameForQuestion($questionId).'</h4>';
  547. $content .= "</div>";
  548. }
  549. return $content;
  550. }
  551. /**
  552. * Display signs [+] and/or (>0) after question title if question has options
  553. * scoreAlwaysPositive and/or uncheckedMayScore
  554. */
  555. public function displayQuestionOption($in_objQuestion)
  556. {
  557. if ($in_objQuestion->type == MULTIPLE_ANSWER && $in_objQuestion->scoreAlwaysPositive) {
  558. echo "<span style='font-size:75%'> (>0)</span>";
  559. }
  560. if ($in_objQuestion->type == MULTIPLE_ANSWER && $in_objQuestion->uncheckedMayScore) {
  561. echo "<span style='font-size:75%'> [+]</span>";
  562. }
  563. }
  564. /**
  565. * sortTabByBracketLabel ($tabCategoryQuestions)
  566. * key of $tabCategoryQuestions are the category id (0 for not in a category)
  567. * value is the array of question id of this category
  568. * Sort question by Category
  569. */
  570. public static function sortTabByBracketLabel($in_tab)
  571. {
  572. $tabResult = array();
  573. $tabCatName = array(); // tab of category name
  574. while (list($cat_id, $tabquestion) = each($in_tab)) {
  575. $category = new TestCategory();
  576. $category = $category->getCategory($cat_id);
  577. $tabCatName[$cat_id] = $category->name;
  578. }
  579. reset($in_tab);
  580. // sort table by value, keeping keys as they are
  581. asort($tabCatName);
  582. // keys of $tabCatName are keys order for $in_tab
  583. while (list($key, $val) = each($tabCatName)) {
  584. $tabResult[$key] = $in_tab[$key];
  585. }
  586. return $tabResult;
  587. }
  588. /**
  589. * return total score for test exe_id for all question in the category $in_cat_id for user
  590. * If no question for this category, return ""
  591. */
  592. public static function getCatScoreForExeidForUserid($in_cat_id, $in_exe_id, $in_user_id)
  593. {
  594. $tbl_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  595. $tbl_question_rel_category = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  596. $in_cat_id = intval($in_cat_id);
  597. $in_exe_id = intval($in_exe_id);
  598. $in_user_id = intval($in_user_id);
  599. $query = "SELECT DISTINCT
  600. marks, exe_id, user_id, ta.question_id, category_id
  601. FROM $tbl_track_attempt ta , $tbl_question_rel_category qrc
  602. WHERE
  603. ta.question_id=qrc.question_id AND
  604. qrc.category_id=$in_cat_id AND
  605. exe_id=$in_exe_id AND user_id=$in_user_id";
  606. $res = Database::query($query);
  607. $totalcatscore = "";
  608. while ($data = Database::fetch_array($res)) {
  609. $totalcatscore += $data['marks'];
  610. }
  611. return $totalcatscore;
  612. }
  613. /**
  614. * return the number max of question in a category
  615. * count the number of questions in all categories, and return the max
  616. * @param int $exerciseId
  617. * @author - hubert borderiou
  618. */
  619. public static function getNumberMaxQuestionByCat($exerciseId)
  620. {
  621. $res_num_max = 0;
  622. // foreach question
  623. $categories = TestCategory::getListOfCategoriesIDForTest($exerciseId);
  624. foreach ($categories as $category) {
  625. if (empty($category['id'])) {
  626. continue;
  627. }
  628. $nbQuestionInThisCat = TestCategory::getNumberOfQuestionsInCategoryForTest($exerciseId, $category['id']);
  629. if ($nbQuestionInThisCat > $res_num_max) {
  630. $res_num_max = $nbQuestionInThisCat;
  631. }
  632. }
  633. return $res_num_max;
  634. }
  635. /**
  636. * Returns a category summary report
  637. * @params int exercise id
  638. * @params array pre filled array with the category_id, score, and weight
  639. * example: array(1 => array('score' => '10', 'total' => 20));
  640. */
  641. public static function get_stats_table_by_attempt($exercise_id, $category_list = array())
  642. {
  643. if (empty($category_list)) {
  644. return null;
  645. }
  646. $category_name_list = TestCategory::getListOfCategoriesNameForTest($exercise_id);
  647. $table = new HTML_Table(array('class' => 'data_table'));
  648. $table->setHeaderContents(0, 0, get_lang('Categories'));
  649. $table->setHeaderContents(0, 1, get_lang('AbsoluteScore'));
  650. $table->setHeaderContents(0, 2, get_lang('RelativeScore'));
  651. $row = 1;
  652. $none_category = array();
  653. if (isset($category_list['none'])) {
  654. $none_category = $category_list['none'];
  655. unset($category_list['none']);
  656. }
  657. $total = array();
  658. if (isset($category_list['total'])) {
  659. $total = $category_list['total'];
  660. unset($category_list['total']);
  661. }
  662. if (count($category_list) > 1) {
  663. foreach ($category_list as $category_id => $category_item) {
  664. $table->setCellContents($row, 0, $category_name_list[$category_id]);
  665. $table->setCellContents($row, 1, ExerciseLib::show_score($category_item['score'], $category_item['total'], false));
  666. $table->setCellContents($row, 2, ExerciseLib::show_score($category_item['score'], $category_item['total'], true, false, true));
  667. $row++;
  668. }
  669. if (!empty($none_category)) {
  670. $table->setCellContents($row, 0, get_lang('None'));
  671. $table->setCellContents($row, 1, ExerciseLib::show_score($none_category['score'], $none_category['total'], false));
  672. $table->setCellContents($row, 2, ExerciseLib::show_score($none_category['score'], $none_category['total'], true, false, true));
  673. $row++;
  674. }
  675. if (!empty($total)) {
  676. $table->setCellContents($row, 0, get_lang('Total'));
  677. $table->setCellContents($row, 1, ExerciseLib::show_score($total['score'], $total['total'], false));
  678. $table->setCellContents($row, 2, ExerciseLib::show_score($total['score'], $total['total'], true, false, true));
  679. }
  680. return $table->toHtml();
  681. }
  682. return null;
  683. }
  684. /**
  685. * @return array
  686. */
  687. public static function get_all_categories()
  688. {
  689. $table = Database::get_course_table(TABLE_QUIZ_CATEGORY);
  690. $sql = "SELECT * FROM $table ORDER BY title ASC";
  691. $res = Database::query($sql);
  692. $array = [];
  693. while ($row = Database::fetch_array($res,'ASSOC')) {
  694. $array[] = $row;
  695. }
  696. return $array;
  697. }
  698. /**
  699. * @param Exercise $exercise
  700. * @param int $course_id
  701. * @param string $order
  702. * @param bool $shuffle
  703. * @param bool $excludeCategoryWithNoQuestions
  704. * @return array|bool
  705. */
  706. public function getCategoryExerciseTree(
  707. $exercise,
  708. $course_id,
  709. $order = null,
  710. $shuffle = false,
  711. $excludeCategoryWithNoQuestions = true
  712. ) {
  713. if (empty($exercise)) {
  714. return array();
  715. }
  716. if (!$exercise->specialCategoryOrders) {
  717. return false;
  718. }
  719. $course_id = intval($course_id);
  720. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  721. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  722. $sql = "SELECT * FROM $table qc
  723. LEFT JOIN $categoryTable c
  724. ON (qc.c_id = c.c_id AND c.id = qc.category_id)
  725. WHERE qc.c_id = $course_id AND exercise_id = {$exercise->id} ";
  726. if (!empty($order)) {
  727. $sql .= "ORDER BY $order";
  728. }
  729. $categories = array();
  730. $result = Database::query($sql);
  731. if (Database::num_rows($result)) {
  732. while ($row = Database::fetch_array($result, 'ASSOC')) {
  733. if ($excludeCategoryWithNoQuestions) {
  734. if ($row['count_questions'] == 0) {
  735. continue;
  736. }
  737. }
  738. if (empty($row['title']) && empty($row['category_id'])) {
  739. $row['title'] = get_lang('NoCategory');
  740. }
  741. $categories[$row['category_id']] = $row;
  742. }
  743. }
  744. if ($shuffle) {
  745. shuffle_assoc($categories);
  746. }
  747. return $categories;
  748. }
  749. /**
  750. * @param $form
  751. * @param string $action
  752. */
  753. public function getForm(& $form, $action = 'new')
  754. {
  755. switch($action) {
  756. case 'new':
  757. $header = get_lang('AddACategory');
  758. $submit = get_lang('AddTestCategory');
  759. break;
  760. case 'edit':
  761. $header = get_lang('EditCategory');
  762. $submit = get_lang('ModifyCategory');
  763. break;
  764. }
  765. // settting the form elements
  766. $form->addElement('header', $header);
  767. $form->addElement('hidden', 'category_id');
  768. $form->addElement('text', 'category_name', get_lang('CategoryName'), array('class' => 'span6'));
  769. $form->add_html_editor('category_description', get_lang('CategoryDescription'), false, false, array('ToolbarSet' => 'test_category', 'Width' => '90%', 'Height' => '200'));
  770. $category_parent_list = array();
  771. $options = array(
  772. '1' => get_lang('Visible'),
  773. '0' => get_lang('Hidden')
  774. );
  775. $form->addElement('select', 'visibility', get_lang('Visibility'), $options);
  776. $script = null;
  777. if (!empty($this->parent_id)) {
  778. $parent_cat = new TestCategory();
  779. $parent_cat = $parent_cat->getCategory($this->parent_id);
  780. $category_parent_list = array($parent_cat->id => $parent_cat->name);
  781. $script .= '<script>$(function() { $("#parent_id").trigger("addItem",[{"title": "'.$parent_cat->name.'", "value": "'.$parent_cat->id.'"}]); });</script>';
  782. }
  783. $form->addElement('html', $script);
  784. $form->addElement('select', 'parent_id', get_lang('Parent'), $category_parent_list, array('id' => 'parent_id'));
  785. $form->addElement('style_submit_button', 'SubmitNote', $submit, 'class="add"');
  786. // setting the defaults
  787. $defaults = array();
  788. $defaults["category_id"] = $this->id;
  789. $defaults["category_name"] = $this->name;
  790. $defaults["category_description"] = $this->description;
  791. $defaults["parent_id"] = $this->parent_id;
  792. $defaults["visibility"] = $this->visibility;
  793. $form->setDefaults($defaults);
  794. // setting the rules
  795. $form->addRule('category_name', get_lang('ThisFieldIsRequired'), 'required');
  796. }
  797. /**
  798. * Returns the category form.
  799. * @param Exercise $exercise_obj
  800. * @return string
  801. */
  802. public function returnCategoryForm(Exercise $exercise_obj)
  803. {
  804. $categories = $this->getListOfCategoriesForTest($exercise_obj);
  805. $saved_categories = $exercise_obj->get_categories_in_exercise();
  806. $return = null;
  807. if (!empty($categories)) {
  808. $nbQuestionsTotal = $exercise_obj->getNumberQuestionExerciseCategory();
  809. $exercise_obj->setCategoriesGrouping(true);
  810. $real_question_count = count($exercise_obj->getQuestionList());
  811. $warning = null;
  812. if ($nbQuestionsTotal != $real_question_count) {
  813. $warning = Display::return_message(get_lang('CheckThatYouHaveEnoughQuestionsInYourCategories'), 'warning');
  814. }
  815. $return .= $warning;
  816. $return .= '<table class="data_table">';
  817. $return .= '<tr>';
  818. $return .= '<th height="24">' . get_lang('Categories') . '</th>';
  819. $return .= '<th width="70" height="24">' . get_lang('Number') . '</th></tr>';
  820. $emptyCategory = array(
  821. 'id' => '0',
  822. 'name' => get_lang('NoCategory'),
  823. 'description' => '',
  824. 'iid' => '0',
  825. 'title' => get_lang('NoCategory')
  826. );
  827. $categories[] = $emptyCategory;
  828. foreach ($categories as $category) {
  829. $cat_id = $category['iid'];
  830. $return .= '<tr>';
  831. $return .= '<td>';
  832. //$return .= Display::div(isset($category['parent_path']) ? $category['parent_path'] : '');
  833. $return .= Display::div($category['name']);
  834. $return .= '</td>';
  835. $return .= '<td>';
  836. $value = isset($saved_categories) && isset($saved_categories[$cat_id]) ? $saved_categories[$cat_id]['count_questions'] : -1;
  837. $return .= '<input name="category['.$cat_id.']" value="' .$value.'" />';
  838. $return .= '</td>';
  839. $return .= '</tr>';
  840. }
  841. $return .= '</table>';
  842. $return .= get_lang('ZeroMeansNoQuestionWillBeSelectedMinusOneMeansThatAllQuestionsWillBeSelected');
  843. return $return;
  844. }
  845. }
  846. /**
  847. * Sorts an array
  848. * @param $array
  849. * @return mixed
  850. */
  851. public function sort_tree_array($array)
  852. {
  853. foreach ($array as $key => $row) {
  854. $parent[$key] = $row['parent_id'];
  855. }
  856. if (count($array) > 0) {
  857. array_multisort($parent, SORT_ASC, $array);
  858. }
  859. return $array;
  860. }
  861. /**
  862. * Return true if a category already exists with the same name
  863. * @param string $name
  864. *
  865. * @return bool
  866. */
  867. public static function category_exists_with_title($name)
  868. {
  869. $categories = TestCategory::getCategoryListInfo('title');
  870. foreach ($categories as $title) {
  871. if ($title == $name) {
  872. return true;
  873. }
  874. }
  875. return false;
  876. }
  877. /**
  878. * Return the id of the test category with title = $in_title
  879. * @param $in_title
  880. *
  881. * @return int is id of test category
  882. */
  883. public static function get_category_id_for_title($title, $courseId = 0)
  884. {
  885. $out_res = 0;
  886. if (empty($courseId)) {
  887. $courseId = api_get_course_int_id();
  888. }
  889. $courseId = intval($courseId);
  890. $tbl_cat = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  891. $sql = "SELECT id FROM $tbl_cat
  892. WHERE c_id = $courseId AND title = '".Database::escape_string($title)."'";
  893. $res = Database::query($sql);
  894. if (Database::num_rows($res) > 0) {
  895. $data = Database::fetch_array($res);
  896. $out_res = $data['id'];
  897. }
  898. return $out_res;
  899. }
  900. /**
  901. * Add a relation between question and category in table c_quiz_question_rel_category
  902. * @param int $categoryId
  903. * @param int $questionId
  904. * @param int $courseId
  905. *
  906. * @return string|false
  907. */
  908. public static function add_category_for_question_id($categoryId, $questionId, $courseId)
  909. {
  910. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  911. // if question doesn't have a category
  912. // @todo change for 1.10 when a question can have several categories
  913. if (TestCategory::getCategoryForQuestion($questionId, $courseId) == 0 &&
  914. $questionId > 0 &&
  915. $courseId > 0
  916. ) {
  917. $sql = "INSERT INTO $table (c_id, question_id, category_id)
  918. VALUES (".intval($courseId).", ".intval($questionId).", ".intval($categoryId).")";
  919. Database::query($sql);
  920. $id = Database::insert_id();
  921. return $id;
  922. }
  923. return false;
  924. }
  925. /**
  926. * @param int $courseId
  927. * @param int $sessionId
  928. *
  929. * @return array
  930. */
  931. public function getCategories($courseId, $sessionId = 0)
  932. {
  933. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  934. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  935. $sessionId = intval($sessionId);
  936. $courseId = intval($courseId);
  937. if (empty($sessionId)) {
  938. $sessionCondition = api_get_session_condition($sessionId, true, false, 'i.session_id');
  939. } else {
  940. $sessionCondition = api_get_session_condition($sessionId, true, true, 'i.session_id');
  941. }
  942. if (empty($courseId)) {
  943. return array();
  944. }
  945. $sql = "SELECT c.* FROM $table c
  946. INNER JOIN $itemProperty i
  947. ON c.c_id = i.c_id AND i.ref = c.id
  948. WHERE
  949. c.c_id = $courseId AND
  950. i.tool = '".TOOL_TEST_CATEGORY."'
  951. $sessionCondition
  952. ORDER BY title";
  953. $result = Database::query($sql);
  954. return Database::store_result($result, 'ASSOC');
  955. }
  956. /**
  957. * @param int $courseId
  958. * @param int $sessionId
  959. * @return string
  960. */
  961. public function displayCategories($courseId, $sessionId = 0)
  962. {
  963. $categories = $this->getCategories($courseId, $sessionId);
  964. $html = '';
  965. foreach ($categories as $category) {
  966. $tmpobj = new TestCategory();
  967. $tmpobj = $tmpobj->getCategory($category['id']);
  968. $nb_question = $tmpobj->getCategoryQuestionsNumber();
  969. $rowname = self::protectJSDialogQuote($category['title']);
  970. $nb_question_label = $nb_question == 1 ? $nb_question . ' ' . get_lang('Question') : $nb_question . ' ' . get_lang('Questions');
  971. //$html .= '<div class="sectiontitle" id="id_cat' . $category['id'] . '">';
  972. $content = "<span style='float:right'>" . $nb_question_label . "</span>";
  973. $content .= '<div class="sectioncomment">';
  974. $content .= $category['description'];
  975. $content .= '</div>';
  976. $links = '<a href="' . api_get_self() . '?action=editcategory&category_id=' . $category['id'] . '&'.api_get_cidreq().'">' .
  977. Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>';
  978. $links .= ' <a href="' . api_get_self() . '?'.api_get_cidreq().'&action=deletecategory&category_id=' . $category['id'] . '" ';
  979. $links .= 'onclick="return confirmDelete(\'' . self::protectJSDialogQuote(get_lang('DeleteCategoryAreYouSure') . '[' . $rowname) . '] ?\', \'id_cat' . $category['id'] . '\');">';
  980. $links .= Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
  981. $html .= Display::panel($content, $category['title'].$links);
  982. }
  983. return $html;
  984. }
  985. // To allowed " in javascript dialog box without bad surprises
  986. // replace " with two '
  987. public function protectJSDialogQuote($in_txt)
  988. {
  989. $res = $in_txt;
  990. $res = str_replace("'", "\'", $res);
  991. $res = str_replace('"', "\'\'", $res); // super astuce pour afficher les " dans les boite de dialogue
  992. return $res;
  993. }
  994. }