TestCategory.php 37 KB

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