TestCategory.php 41 KB

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