TestCategory.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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. }