TestCategory.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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. * true if question id has a category.
  253. *
  254. * @param int $questionId
  255. *
  256. * @return bool
  257. */
  258. public static function isQuestionHasCategory($questionId)
  259. {
  260. if (self::getCategoryForQuestion($questionId) > 0) {
  261. return true;
  262. }
  263. return false;
  264. }
  265. /**
  266. * Return the category name for question with question_id = $questionId
  267. * In this version, a question has only 1 category.
  268. *
  269. * @param $questionId
  270. * @param int $courseId
  271. *
  272. * @return string
  273. */
  274. public static function getCategoryNameForQuestion($questionId, $courseId = 0)
  275. {
  276. if (empty($courseId)) {
  277. $courseId = api_get_course_int_id();
  278. }
  279. $courseId = (int) $courseId;
  280. $categoryId = self::getCategoryForQuestion($questionId, $courseId);
  281. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  282. $sql = "SELECT title
  283. FROM $table
  284. WHERE id = $categoryId AND c_id = $courseId";
  285. $res = Database::query($sql);
  286. $data = Database::fetch_array($res);
  287. $result = '';
  288. if (Database::num_rows($res) > 0) {
  289. $result = $data['title'];
  290. }
  291. return $result;
  292. }
  293. /**
  294. * Return the list of differents categories ID for a test in the current course
  295. * input : test_id
  296. * return : array of category id (integer)
  297. * hubert.borderiou 07-04-2011.
  298. *
  299. * @param int $exerciseId
  300. * @param int $courseId
  301. *
  302. * @return array
  303. */
  304. public static function getListOfCategoriesIDForTest($exerciseId, $courseId = 0)
  305. {
  306. // parcourir les questions d'un test, recup les categories uniques dans un tableau
  307. $exercise = new Exercise($courseId);
  308. $exercise->read($exerciseId, false);
  309. $categoriesInExercise = $exercise->getQuestionWithCategories();
  310. // the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???
  311. $categories = [];
  312. if (!empty($categoriesInExercise)) {
  313. foreach ($categoriesInExercise as $category) {
  314. $categories[$category['id']] = $category;
  315. }
  316. }
  317. return $categories;
  318. }
  319. /**
  320. * @param Exercise $exercise
  321. *
  322. * @return array
  323. */
  324. public static function getListOfCategoriesIDForTestObject(Exercise $exercise)
  325. {
  326. // parcourir les questions d'un test, recup les categories uniques dans un tableau
  327. $categories_in_exercise = [];
  328. $question_list = $exercise->getQuestionOrderedListByName();
  329. // the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???
  330. foreach ($question_list as $questionInfo) {
  331. $question_id = $questionInfo['question_id'];
  332. $category_list = self::getCategoryForQuestion($question_id);
  333. if (is_numeric($category_list)) {
  334. $category_list = [$category_list];
  335. }
  336. if (!empty($category_list)) {
  337. $categories_in_exercise = array_merge($categories_in_exercise, $category_list);
  338. }
  339. }
  340. if (!empty($categories_in_exercise)) {
  341. $categories_in_exercise = array_unique(array_filter($categories_in_exercise));
  342. }
  343. return $categories_in_exercise;
  344. }
  345. /**
  346. * Return the list of different categories NAME for a test.
  347. *
  348. * @param int $exerciseId
  349. * @param bool
  350. *
  351. * @return array
  352. *
  353. * @author function rewrote by jmontoya
  354. */
  355. public static function getListOfCategoriesNameForTest($exerciseId, $grouped_by_category = true)
  356. {
  357. $result = [];
  358. $categories = self::getListOfCategoriesIDForTest($exerciseId);
  359. foreach ($categories as $catInfo) {
  360. $categoryId = $catInfo['id'];
  361. if (!empty($categoryId)) {
  362. $result[$categoryId] = [
  363. 'title' => $catInfo['title'],
  364. //'parent_id' => $catInfo['parent_id'],
  365. 'parent_id' => '',
  366. 'c_id' => $catInfo['c_id'],
  367. ];
  368. }
  369. }
  370. return $result;
  371. }
  372. /**
  373. * @param Exercise $exercise
  374. *
  375. * @return array
  376. */
  377. public static function getListOfCategoriesForTest(Exercise $exercise)
  378. {
  379. $result = [];
  380. $categories = self::getListOfCategoriesIDForTestObject($exercise);
  381. foreach ($categories as $cat_id) {
  382. $cat = new TestCategory();
  383. $cat = (array) $cat->getCategory($cat_id);
  384. $cat['iid'] = $cat['id'];
  385. $cat['title'] = $cat['name'];
  386. $result[$cat['id']] = $cat;
  387. }
  388. return $result;
  389. }
  390. /**
  391. * return the number of differents categories for a test
  392. * input : test_id
  393. * return : integer
  394. * hubert.borderiou 07-04-2011.
  395. */
  396. public static function getNumberOfCategoriesForTest($id)
  397. {
  398. return count(self::getListOfCategoriesIDForTest($id));
  399. }
  400. /**
  401. * return the number of question of a category id in a test.
  402. *
  403. * @param int $exerciseId
  404. * @param int $categoryId
  405. *
  406. * @return int
  407. *
  408. * @author hubert.borderiou 07-04-2011
  409. */
  410. public static function getNumberOfQuestionsInCategoryForTest($exerciseId, $categoryId)
  411. {
  412. $nbCatResult = 0;
  413. $quiz = new Exercise();
  414. $quiz->read($exerciseId);
  415. $questionList = $quiz->selectQuestionList();
  416. // the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ? ? ?
  417. for ($i = 1; $i <= count($questionList); $i++) {
  418. if (self::getCategoryForQuestion($questionList[$i]) == $categoryId) {
  419. $nbCatResult++;
  420. }
  421. }
  422. return $nbCatResult;
  423. }
  424. /**
  425. * return the number of question for a test using random by category
  426. * input : test_id, number of random question (min 1).
  427. *
  428. * @param int $exerciseId
  429. * @param int $random
  430. *
  431. * @return int
  432. * hubert.borderiou 07-04-2011
  433. * question without categories are not counted
  434. */
  435. public static function getNumberOfQuestionRandomByCategory($exerciseId, $random)
  436. {
  437. $count = 0;
  438. $categories = self::getListOfCategoriesIDForTest($exerciseId);
  439. foreach ($categories as $category) {
  440. if (empty($category['id'])) {
  441. continue;
  442. }
  443. $nbQuestionInThisCat = self::getNumberOfQuestionsInCategoryForTest(
  444. $exerciseId,
  445. $category['id']
  446. );
  447. if ($nbQuestionInThisCat > $random) {
  448. $count += $random;
  449. } else {
  450. $count += $nbQuestionInThisCat;
  451. }
  452. }
  453. return $count;
  454. }
  455. /**
  456. * Return an array (id=>name)
  457. * array[0] = get_lang('NoCategory');.
  458. *
  459. * @param int $courseId
  460. *
  461. * @return array
  462. */
  463. public static function getCategoriesIdAndName($courseId = 0)
  464. {
  465. if (empty($courseId)) {
  466. $courseId = api_get_course_int_id();
  467. }
  468. $categories = self::getCategoryListInfo('', $courseId);
  469. $result = ['0' => get_lang('NoCategorySelected')];
  470. for ($i = 0; $i < count($categories); $i++) {
  471. $result[$categories[$i]->id] = $categories[$i]->name;
  472. }
  473. return $result;
  474. }
  475. /**
  476. * Returns an array of question ids for each category
  477. * $categories[1][30] = 10, array with category id = 1 and question_id = 10
  478. * A question has "n" categories.
  479. *
  480. * @param int $exerciseId
  481. * @param array $check_in_question_list
  482. * @param array $categoriesAddedInExercise
  483. *
  484. * @return array
  485. */
  486. public static function getQuestionsByCat(
  487. $exerciseId,
  488. $check_in_question_list = [],
  489. $categoriesAddedInExercise = []
  490. ) {
  491. $tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
  492. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  493. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  494. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  495. $exerciseId = (int) $exerciseId;
  496. $courseId = api_get_course_int_id();
  497. $sql = "SELECT DISTINCT qrc.question_id, qrc.category_id
  498. FROM $TBL_QUESTION_REL_CATEGORY qrc
  499. INNER JOIN $TBL_EXERCICE_QUESTION eq
  500. ON (eq.question_id = qrc.question_id AND qrc.c_id = eq.c_id)
  501. INNER JOIN $categoryTable c
  502. ON (c.id = qrc.category_id AND c.c_id = eq.c_id)
  503. INNER JOIN $tableQuestion q
  504. ON (q.id = qrc.question_id AND q.c_id = eq.c_id)
  505. WHERE
  506. exercice_id = $exerciseId AND
  507. qrc.c_id = $courseId
  508. ";
  509. $res = Database::query($sql);
  510. $categories = [];
  511. while ($data = Database::fetch_array($res)) {
  512. if (!empty($check_in_question_list)) {
  513. if (!in_array($data['question_id'], $check_in_question_list)) {
  514. continue;
  515. }
  516. }
  517. if (!isset($categories[$data['category_id']]) ||
  518. !is_array($categories[$data['category_id']])
  519. ) {
  520. $categories[$data['category_id']] = [];
  521. }
  522. $categories[$data['category_id']][] = $data['question_id'];
  523. }
  524. if (!empty($categoriesAddedInExercise)) {
  525. $newCategoryList = [];
  526. foreach ($categoriesAddedInExercise as $category) {
  527. $categoryId = $category['category_id'];
  528. if (isset($categories[$categoryId])) {
  529. $newCategoryList[$categoryId] = $categories[$categoryId];
  530. }
  531. }
  532. $checkQuestionsWithNoCategory = false;
  533. foreach ($categoriesAddedInExercise as $category) {
  534. if (empty($category['category_id'])) {
  535. // Check
  536. $checkQuestionsWithNoCategory = true;
  537. break;
  538. }
  539. }
  540. // Select questions that don't have any category related
  541. if ($checkQuestionsWithNoCategory) {
  542. $originalQuestionList = $check_in_question_list;
  543. foreach ($originalQuestionList as $questionId) {
  544. $categoriesFlatten = array_flatten($categories);
  545. if (!in_array($questionId, $categoriesFlatten)) {
  546. $newCategoryList[0][] = $questionId;
  547. }
  548. }
  549. }
  550. $categories = $newCategoryList;
  551. }
  552. return $categories;
  553. }
  554. /**
  555. * Returns an array of $numberElements from $array.
  556. *
  557. * @param array
  558. * @param int
  559. *
  560. * @return array
  561. */
  562. public static function getNElementsFromArray($array, $numberElements)
  563. {
  564. $list = $array;
  565. shuffle($list);
  566. if ($numberElements < count($list)) {
  567. $list = array_slice($list, 0, $numberElements);
  568. }
  569. return $list;
  570. }
  571. /**
  572. * @param int $questionId
  573. * @param int $displayCategoryName
  574. */
  575. public static function displayCategoryAndTitle($questionId, $displayCategoryName = 1)
  576. {
  577. echo self::returnCategoryAndTitle($questionId, $displayCategoryName);
  578. }
  579. /**
  580. * @param int $questionId
  581. * @param int $in_display_category_name
  582. *
  583. * @return string|null
  584. */
  585. public static function returnCategoryAndTitle($questionId, $in_display_category_name = 1)
  586. {
  587. $is_student = !(api_is_allowed_to_edit(null, true) || api_is_session_admin());
  588. $objExercise = Session::read('objExercise');
  589. if (!empty($objExercise)) {
  590. $in_display_category_name = $objExercise->display_category_name;
  591. }
  592. $content = null;
  593. if (self::getCategoryNameForQuestion($questionId) != '' &&
  594. ($in_display_category_name == 1 || !$is_student)
  595. ) {
  596. $content .= '<div class="page-header">';
  597. $content .= '<h4>'.get_lang('Category').": ".self::getCategoryNameForQuestion($questionId).'</h4>';
  598. $content .= "</div>";
  599. }
  600. return $content;
  601. }
  602. /**
  603. * Display signs [+] and/or (>0) after question title if question has options
  604. * scoreAlwaysPositive and/or uncheckedMayScore.
  605. *
  606. * @param $objQuestion
  607. */
  608. public function displayQuestionOption($objQuestion)
  609. {
  610. if ($objQuestion->type == MULTIPLE_ANSWER && $objQuestion->scoreAlwaysPositive) {
  611. echo "<span style='font-size:75%'> (>0)</span>";
  612. }
  613. if ($objQuestion->type == MULTIPLE_ANSWER && $objQuestion->uncheckedMayScore) {
  614. echo "<span style='font-size:75%'> [+]</span>";
  615. }
  616. }
  617. /**
  618. * sortTabByBracketLabel ($tabCategoryQuestions)
  619. * key of $tabCategoryQuestions are the category id (0 for not in a category)
  620. * value is the array of question id of this category
  621. * Sort question by Category.
  622. */
  623. public static function sortTabByBracketLabel($in_tab)
  624. {
  625. $tabResult = [];
  626. $tabCatName = []; // tab of category name
  627. foreach ($in_tab as $cat_id => $tabquestion) {
  628. $category = new TestCategory();
  629. $category = $category->getCategory($cat_id);
  630. $tabCatName[$cat_id] = $category->name;
  631. }
  632. reset($in_tab);
  633. // sort table by value, keeping keys as they are
  634. asort($tabCatName);
  635. // keys of $tabCatName are keys order for $in_tab
  636. foreach ($tabCatName as $key => $val) {
  637. $tabResult[$key] = $in_tab[$key];
  638. }
  639. return $tabResult;
  640. }
  641. /**
  642. * Return the number max of question in a category
  643. * count the number of questions in all categories, and return the max.
  644. *
  645. * @param int $exerciseId
  646. *
  647. * @author - hubert borderiou
  648. *
  649. * @return int
  650. */
  651. public static function getNumberMaxQuestionByCat($exerciseId)
  652. {
  653. $res_num_max = 0;
  654. // foreach question
  655. $categories = self::getListOfCategoriesIDForTest($exerciseId);
  656. foreach ($categories as $category) {
  657. if (empty($category['id'])) {
  658. continue;
  659. }
  660. $nbQuestionInThisCat = self::getNumberOfQuestionsInCategoryForTest(
  661. $exerciseId,
  662. $category['id']
  663. );
  664. if ($nbQuestionInThisCat > $res_num_max) {
  665. $res_num_max = $nbQuestionInThisCat;
  666. }
  667. }
  668. return $res_num_max;
  669. }
  670. /**
  671. * Returns a category summary report.
  672. *
  673. * @param int $exerciseId
  674. * @param array $category_list
  675. * pre filled array with the category_id, score, and weight
  676. * example: array(1 => array('score' => '10', 'total' => 20));
  677. *
  678. * @return string
  679. */
  680. public static function get_stats_table_by_attempt(
  681. $exerciseId,
  682. $category_list = []
  683. ) {
  684. if (empty($category_list)) {
  685. return null;
  686. }
  687. $category_name_list = self::getListOfCategoriesNameForTest($exerciseId);
  688. $table = new HTML_Table(['class' => 'table table-bordered', 'id' => 'category_results']);
  689. $table->setHeaderContents(0, 0, get_lang('Categories'));
  690. $table->setHeaderContents(0, 1, get_lang('AbsoluteScore'));
  691. $table->setHeaderContents(0, 2, get_lang('RelativeScore'));
  692. $row = 1;
  693. $none_category = [];
  694. if (isset($category_list['none'])) {
  695. $none_category = $category_list['none'];
  696. unset($category_list['none']);
  697. }
  698. $total = [];
  699. if (isset($category_list['total'])) {
  700. $total = $category_list['total'];
  701. unset($category_list['total']);
  702. }
  703. if (count($category_list) > 1) {
  704. foreach ($category_list as $category_id => $category_item) {
  705. $table->setCellContents($row, 0, $category_name_list[$category_id]);
  706. $table->setCellContents(
  707. $row,
  708. 1,
  709. ExerciseLib::show_score(
  710. $category_item['score'],
  711. $category_item['total'],
  712. false
  713. )
  714. );
  715. $table->setCellContents(
  716. $row,
  717. 2,
  718. ExerciseLib::show_score(
  719. $category_item['score'],
  720. $category_item['total'],
  721. true,
  722. false,
  723. true
  724. )
  725. );
  726. $row++;
  727. }
  728. if (!empty($none_category)) {
  729. $table->setCellContents($row, 0, get_lang('None'));
  730. $table->setCellContents(
  731. $row,
  732. 1,
  733. ExerciseLib::show_score(
  734. $none_category['score'],
  735. $none_category['total'],
  736. false
  737. )
  738. );
  739. $table->setCellContents(
  740. $row,
  741. 2,
  742. ExerciseLib::show_score(
  743. $none_category['score'],
  744. $none_category['total'],
  745. true,
  746. false,
  747. true
  748. )
  749. );
  750. $row++;
  751. }
  752. if (!empty($total)) {
  753. $table->setCellContents($row, 0, get_lang('Total'));
  754. $table->setCellContents(
  755. $row,
  756. 1,
  757. ExerciseLib::show_score(
  758. $total['score'],
  759. $total['total'],
  760. false
  761. )
  762. );
  763. $table->setCellContents(
  764. $row,
  765. 2,
  766. ExerciseLib::show_score(
  767. $total['score'],
  768. $total['total'],
  769. true,
  770. false,
  771. true
  772. )
  773. );
  774. }
  775. return $table->toHtml();
  776. }
  777. return '';
  778. }
  779. /**
  780. * @return array
  781. */
  782. public static function get_all_categories()
  783. {
  784. $table = Database::get_course_table(TABLE_QUIZ_CATEGORY);
  785. $sql = "SELECT * FROM $table ORDER BY title ASC";
  786. $res = Database::query($sql);
  787. $array = [];
  788. while ($row = Database::fetch_array($res, 'ASSOC')) {
  789. $array[] = $row;
  790. }
  791. return $array;
  792. }
  793. /**
  794. * @param Exercise $exercise
  795. * @param int $courseId
  796. * @param string $order
  797. * @param bool $shuffle
  798. * @param bool $excludeCategoryWithNoQuestions
  799. *
  800. * @return array
  801. */
  802. public function getCategoryExerciseTree(
  803. $exercise,
  804. $courseId,
  805. $order = null,
  806. $shuffle = false,
  807. $excludeCategoryWithNoQuestions = true
  808. ) {
  809. if (empty($exercise)) {
  810. return [];
  811. }
  812. $courseId = (int) $courseId;
  813. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  814. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  815. $exercise->id = (int) $exercise->id;
  816. $sql = "SELECT * FROM $table qc
  817. LEFT JOIN $categoryTable c
  818. ON (qc.c_id = c.c_id AND c.id = qc.category_id)
  819. WHERE qc.c_id = $courseId AND exercise_id = {$exercise->id} ";
  820. if (!empty($order)) {
  821. $order = Database::escape_string($order);
  822. $sql .= "ORDER BY $order";
  823. }
  824. $categories = [];
  825. $result = Database::query($sql);
  826. if (Database::num_rows($result)) {
  827. while ($row = Database::fetch_array($result, 'ASSOC')) {
  828. if ($excludeCategoryWithNoQuestions) {
  829. if ($row['count_questions'] == 0) {
  830. continue;
  831. }
  832. }
  833. if (empty($row['title']) && empty($row['category_id'])) {
  834. $row['title'] = get_lang('NoCategory');
  835. }
  836. $categories[$row['category_id']] = $row;
  837. }
  838. }
  839. if ($shuffle) {
  840. shuffle_assoc($categories);
  841. }
  842. return $categories;
  843. }
  844. /**
  845. * @param FormValidator $form
  846. * @param string $action
  847. */
  848. public function getForm(&$form, $action = 'new')
  849. {
  850. switch ($action) {
  851. case 'new':
  852. $header = get_lang('AddACategory');
  853. $submit = get_lang('AddTestCategory');
  854. break;
  855. case 'edit':
  856. $header = get_lang('EditCategory');
  857. $submit = get_lang('ModifyCategory');
  858. break;
  859. }
  860. // Setting the form elements
  861. $form->addElement('header', $header);
  862. $form->addElement('hidden', 'category_id');
  863. $form->addElement(
  864. 'text',
  865. 'category_name',
  866. get_lang('CategoryName'),
  867. ['class' => 'span6']
  868. );
  869. $form->add_html_editor(
  870. 'category_description',
  871. get_lang('CategoryDescription'),
  872. false,
  873. false,
  874. [
  875. 'ToolbarSet' => 'test_category',
  876. 'Width' => '90%',
  877. 'Height' => '200',
  878. ]
  879. );
  880. $category_parent_list = [];
  881. $options = [
  882. '1' => get_lang('Visible'),
  883. '0' => get_lang('Hidden'),
  884. ];
  885. $form->addElement(
  886. 'select',
  887. 'visibility',
  888. get_lang('Visibility'),
  889. $options
  890. );
  891. $script = null;
  892. if (!empty($this->parent_id)) {
  893. $parent_cat = new TestCategory();
  894. $parent_cat = $parent_cat->getCategory($this->parent_id);
  895. $category_parent_list = [$parent_cat->id => $parent_cat->name];
  896. $script .= '<script>$(function() { $("#parent_id").trigger("addItem",[{"title": "'.$parent_cat->name.'", "value": "'.$parent_cat->id.'"}]); });</script>';
  897. }
  898. $form->addElement('html', $script);
  899. $form->addElement('select', 'parent_id', get_lang('Parent'), $category_parent_list, ['id' => 'parent_id']);
  900. $form->addElement('style_submit_button', 'SubmitNote', $submit, 'class="add"');
  901. // setting the defaults
  902. $defaults = [];
  903. $defaults["category_id"] = $this->id;
  904. $defaults["category_name"] = $this->name;
  905. $defaults["category_description"] = $this->description;
  906. $defaults["parent_id"] = $this->parent_id;
  907. $defaults["visibility"] = $this->visibility;
  908. $form->setDefaults($defaults);
  909. // setting the rules
  910. $form->addRule('category_name', get_lang('ThisFieldIsRequired'), 'required');
  911. }
  912. /**
  913. * Returns the category form.
  914. *
  915. * @param Exercise $exercise
  916. *
  917. * @return string
  918. */
  919. public function returnCategoryForm(Exercise $exercise)
  920. {
  921. $categories = $this->getListOfCategoriesForTest($exercise);
  922. $saved_categories = $exercise->getCategoriesInExercise();
  923. $return = null;
  924. if (!empty($categories)) {
  925. $nbQuestionsTotal = $exercise->getNumberQuestionExerciseCategory();
  926. $exercise->setCategoriesGrouping(true);
  927. $real_question_count = count($exercise->getQuestionList());
  928. $warning = null;
  929. if ($nbQuestionsTotal != $real_question_count) {
  930. $warning = Display::return_message(
  931. get_lang('CheckThatYouHaveEnoughQuestionsInYourCategories'),
  932. 'warning'
  933. );
  934. }
  935. $return .= $warning;
  936. $return .= '<table class="data_table">';
  937. $return .= '<tr>';
  938. $return .= '<th height="24">'.get_lang('Categories').'</th>';
  939. $return .= '<th width="70" height="24">'.get_lang('Number').'</th></tr>';
  940. $emptyCategory = [
  941. 'id' => '0',
  942. 'name' => get_lang('NoCategory'),
  943. 'description' => '',
  944. 'iid' => '0',
  945. 'title' => get_lang('NoCategory'),
  946. ];
  947. $categories[] = $emptyCategory;
  948. foreach ($categories as $category) {
  949. $cat_id = $category['iid'];
  950. $return .= '<tr>';
  951. $return .= '<td>';
  952. $return .= Display::div($category['name']);
  953. $return .= '</td>';
  954. $return .= '<td>';
  955. $value = isset($saved_categories) && isset($saved_categories[$cat_id]) ? $saved_categories[$cat_id]['count_questions'] : -1;
  956. $return .= '<input name="category['.$cat_id.']" value="'.$value.'" />';
  957. $return .= '</td>';
  958. $return .= '</tr>';
  959. }
  960. $return .= '</table>';
  961. $return .= get_lang('ZeroMeansNoQuestionWillBeSelectedMinusOneMeansThatAllQuestionsWillBeSelected');
  962. }
  963. return $return;
  964. }
  965. /**
  966. * Sorts an array.
  967. *
  968. * @param array $array
  969. *
  970. * @return array
  971. */
  972. public function sort_tree_array($array)
  973. {
  974. foreach ($array as $key => $row) {
  975. $parent[$key] = $row['parent_id'];
  976. }
  977. if (count($array) > 0) {
  978. array_multisort($parent, SORT_ASC, $array);
  979. }
  980. return $array;
  981. }
  982. /**
  983. * Return true if a category already exists with the same name.
  984. *
  985. * @param string $name
  986. * @param int $courseId
  987. *
  988. * @return bool
  989. */
  990. public static function categoryTitleExists($name, $courseId = 0)
  991. {
  992. $categories = self::getCategoryListInfo('title', $courseId);
  993. foreach ($categories as $title) {
  994. if ($title == $name) {
  995. return true;
  996. }
  997. }
  998. return false;
  999. }
  1000. /**
  1001. * Return the id of the test category with title = $in_title.
  1002. *
  1003. * @param string $title
  1004. * @param int $courseId
  1005. *
  1006. * @return int is id of test category
  1007. */
  1008. public static function get_category_id_for_title($title, $courseId = 0)
  1009. {
  1010. $out_res = 0;
  1011. if (empty($courseId)) {
  1012. $courseId = api_get_course_int_id();
  1013. }
  1014. $courseId = (int) $courseId;
  1015. $tbl_cat = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  1016. $sql = "SELECT id FROM $tbl_cat
  1017. WHERE c_id = $courseId AND title = '".Database::escape_string($title)."'";
  1018. $res = Database::query($sql);
  1019. if (Database::num_rows($res) > 0) {
  1020. $data = Database::fetch_array($res);
  1021. $out_res = $data['id'];
  1022. }
  1023. return $out_res;
  1024. }
  1025. /**
  1026. * Add a relation between question and category in table c_quiz_question_rel_category.
  1027. *
  1028. * @param int $categoryId
  1029. * @param int $questionId
  1030. * @param int $courseId
  1031. *
  1032. * @return string|false
  1033. */
  1034. public static function addCategoryToQuestion($categoryId, $questionId, $courseId)
  1035. {
  1036. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  1037. // if question doesn't have a category
  1038. // @todo change for 1.10 when a question can have several categories
  1039. if (self::getCategoryForQuestion($questionId, $courseId) == 0 &&
  1040. $questionId > 0 &&
  1041. $courseId > 0
  1042. ) {
  1043. $sql = "INSERT INTO $table (c_id, question_id, category_id)
  1044. VALUES (".intval($courseId).", ".intval($questionId).", ".intval($categoryId).")";
  1045. Database::query($sql);
  1046. $id = Database::insert_id();
  1047. return $id;
  1048. }
  1049. return false;
  1050. }
  1051. /**
  1052. * @param int $courseId
  1053. * @param int $sessionId
  1054. *
  1055. * @return array
  1056. */
  1057. public function getCategories($courseId, $sessionId = 0)
  1058. {
  1059. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  1060. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1061. $sessionId = intval($sessionId);
  1062. $courseId = intval($courseId);
  1063. if (empty($sessionId)) {
  1064. $sessionCondition = api_get_session_condition(
  1065. $sessionId,
  1066. true,
  1067. false,
  1068. 'i.session_id'
  1069. );
  1070. } else {
  1071. $sessionCondition = api_get_session_condition(
  1072. $sessionId,
  1073. true,
  1074. true,
  1075. 'i.session_id'
  1076. );
  1077. }
  1078. if (empty($courseId)) {
  1079. return [];
  1080. }
  1081. $sql = "SELECT c.* FROM $table c
  1082. INNER JOIN $itemProperty i
  1083. ON c.c_id = i.c_id AND i.ref = c.id
  1084. WHERE
  1085. c.c_id = $courseId AND
  1086. i.tool = '".TOOL_TEST_CATEGORY."'
  1087. $sessionCondition
  1088. ORDER BY title";
  1089. $result = Database::query($sql);
  1090. return Database::store_result($result, 'ASSOC');
  1091. }
  1092. /**
  1093. * @param int $courseId
  1094. * @param int $sessionId
  1095. *
  1096. * @return string
  1097. */
  1098. public function displayCategories($courseId, $sessionId = 0)
  1099. {
  1100. $sessionId = (int) $sessionId;
  1101. $categories = $this->getCategories($courseId, $sessionId);
  1102. $html = '';
  1103. foreach ($categories as $category) {
  1104. $tmpobj = new TestCategory();
  1105. $tmpobj = $tmpobj->getCategory($category['id']);
  1106. $nb_question = $tmpobj->getCategoryQuestionsNumber();
  1107. $rowname = self::protectJSDialogQuote($category['title']);
  1108. $nb_question_label = $nb_question == 1 ? $nb_question.' '.get_lang('Question') : $nb_question.' '.get_lang('Questions');
  1109. $content = "<span style='float:right'>".$nb_question_label."</span>";
  1110. $content .= '<div class="sectioncomment">';
  1111. $content .= $category['description'];
  1112. $content .= '</div>';
  1113. $links = '';
  1114. if (!$sessionId) {
  1115. $links .= '<a href="'.api_get_self().'?action=editcategory&category_id='.$category['id'].'&'.api_get_cidreq().'">'.
  1116. Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>';
  1117. $links .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=deletecategory&category_id='.$category['id'].'" ';
  1118. $links .= 'onclick="return confirmDelete(\''.self::protectJSDialogQuote(get_lang('DeleteCategoryAreYouSure').'['.$rowname).'] ?\', \'id_cat'.$category['id'].'\');">';
  1119. $links .= Display::return_icon('delete.png', get_lang('Delete'), [], ICON_SIZE_SMALL).'</a>';
  1120. }
  1121. $html .= Display::panel($content, $category['title'].$links);
  1122. }
  1123. return $html;
  1124. }
  1125. /**
  1126. * To allowed " in javascript dialog box without bad surprises
  1127. * replace " with two '.
  1128. *
  1129. * @param string $text
  1130. *
  1131. * @return mixed
  1132. */
  1133. public function protectJSDialogQuote($text)
  1134. {
  1135. $res = $text;
  1136. $res = str_replace("'", "\'", $res);
  1137. // super astuce pour afficher les " dans les boite de dialogue
  1138. $res = str_replace('"', "\'\'", $res);
  1139. return $res;
  1140. }
  1141. }