TestCategory.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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 total score for test exe_id for all question in the category $in_cat_id for user
  643. * If no question for this category, return "".
  644. */
  645. public static function getCatScoreForExeidForUserid($in_cat_id, $in_exe_id, $in_user_id)
  646. {
  647. $tbl_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  648. $tbl_question_rel_category = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  649. $in_cat_id = (int) $in_cat_id;
  650. $in_exe_id = (int) $in_exe_id;
  651. $in_user_id = (int) $in_user_id;
  652. $query = "SELECT DISTINCT
  653. marks,
  654. exe_id,
  655. user_id,
  656. ta.question_id,
  657. category_id
  658. FROM $tbl_track_attempt ta
  659. INNER JOIN $tbl_question_rel_category qrc
  660. ON (ta.question_id = qrc.question_id)
  661. WHERE
  662. qrc.category_id = $in_cat_id AND
  663. exe_id = $in_exe_id AND
  664. user_id = $in_user_id";
  665. $res = Database::query($query);
  666. $score = '';
  667. while ($data = Database::fetch_array($res)) {
  668. $score += $data['marks'];
  669. }
  670. return $score;
  671. }
  672. /**
  673. * Return the number max of question in a category
  674. * count the number of questions in all categories, and return the max.
  675. *
  676. * @param int $exerciseId
  677. *
  678. * @author - hubert borderiou
  679. *
  680. * @return int
  681. */
  682. public static function getNumberMaxQuestionByCat($exerciseId)
  683. {
  684. $res_num_max = 0;
  685. // foreach question
  686. $categories = self::getListOfCategoriesIDForTest($exerciseId);
  687. foreach ($categories as $category) {
  688. if (empty($category['id'])) {
  689. continue;
  690. }
  691. $nbQuestionInThisCat = self::getNumberOfQuestionsInCategoryForTest(
  692. $exerciseId,
  693. $category['id']
  694. );
  695. if ($nbQuestionInThisCat > $res_num_max) {
  696. $res_num_max = $nbQuestionInThisCat;
  697. }
  698. }
  699. return $res_num_max;
  700. }
  701. /**
  702. * Returns a category summary report.
  703. *
  704. * @param int $exerciseId
  705. * @param array $category_list
  706. * pre filled array with the category_id, score, and weight
  707. * example: array(1 => array('score' => '10', 'total' => 20));
  708. *
  709. * @return string
  710. */
  711. public static function get_stats_table_by_attempt(
  712. $exerciseId,
  713. $category_list = []
  714. ) {
  715. if (empty($category_list)) {
  716. return null;
  717. }
  718. $category_name_list = self::getListOfCategoriesNameForTest($exerciseId);
  719. $table = new HTML_Table(['class' => 'table table-bordered', 'id' => 'category_results']);
  720. $table->setHeaderContents(0, 0, get_lang('Categories'));
  721. $table->setHeaderContents(0, 1, get_lang('AbsoluteScore'));
  722. $table->setHeaderContents(0, 2, get_lang('RelativeScore'));
  723. $row = 1;
  724. $none_category = [];
  725. if (isset($category_list['none'])) {
  726. $none_category = $category_list['none'];
  727. unset($category_list['none']);
  728. }
  729. $total = [];
  730. if (isset($category_list['total'])) {
  731. $total = $category_list['total'];
  732. unset($category_list['total']);
  733. }
  734. if (count($category_list) > 1) {
  735. foreach ($category_list as $category_id => $category_item) {
  736. $table->setCellContents($row, 0, $category_name_list[$category_id]);
  737. $table->setCellContents(
  738. $row,
  739. 1,
  740. ExerciseLib::show_score(
  741. $category_item['score'],
  742. $category_item['total'],
  743. false
  744. )
  745. );
  746. $table->setCellContents(
  747. $row,
  748. 2,
  749. ExerciseLib::show_score(
  750. $category_item['score'],
  751. $category_item['total'],
  752. true,
  753. false,
  754. true
  755. )
  756. );
  757. $row++;
  758. }
  759. if (!empty($none_category)) {
  760. $table->setCellContents($row, 0, get_lang('None'));
  761. $table->setCellContents(
  762. $row,
  763. 1,
  764. ExerciseLib::show_score(
  765. $none_category['score'],
  766. $none_category['total'],
  767. false
  768. )
  769. );
  770. $table->setCellContents(
  771. $row,
  772. 2,
  773. ExerciseLib::show_score(
  774. $none_category['score'],
  775. $none_category['total'],
  776. true,
  777. false,
  778. true
  779. )
  780. );
  781. $row++;
  782. }
  783. if (!empty($total)) {
  784. $table->setCellContents($row, 0, get_lang('Total'));
  785. $table->setCellContents(
  786. $row,
  787. 1,
  788. ExerciseLib::show_score(
  789. $total['score'],
  790. $total['total'],
  791. false
  792. )
  793. );
  794. $table->setCellContents(
  795. $row,
  796. 2,
  797. ExerciseLib::show_score(
  798. $total['score'],
  799. $total['total'],
  800. true,
  801. false,
  802. true
  803. )
  804. );
  805. }
  806. return $table->toHtml();
  807. }
  808. return '';
  809. }
  810. /**
  811. * @return array
  812. */
  813. public static function get_all_categories()
  814. {
  815. $table = Database::get_course_table(TABLE_QUIZ_CATEGORY);
  816. $sql = "SELECT * FROM $table ORDER BY title ASC";
  817. $res = Database::query($sql);
  818. $array = [];
  819. while ($row = Database::fetch_array($res, 'ASSOC')) {
  820. $array[] = $row;
  821. }
  822. return $array;
  823. }
  824. /**
  825. * @param Exercise $exercise
  826. * @param int $courseId
  827. * @param string $order
  828. * @param bool $shuffle
  829. * @param bool $excludeCategoryWithNoQuestions
  830. *
  831. * @return array
  832. */
  833. public function getCategoryExerciseTree(
  834. $exercise,
  835. $courseId,
  836. $order = null,
  837. $shuffle = false,
  838. $excludeCategoryWithNoQuestions = true
  839. ) {
  840. if (empty($exercise)) {
  841. return [];
  842. }
  843. $courseId = (int) $courseId;
  844. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  845. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  846. $exercise->id = (int) $exercise->id;
  847. $sql = "SELECT * FROM $table qc
  848. LEFT JOIN $categoryTable c
  849. ON (qc.c_id = c.c_id AND c.id = qc.category_id)
  850. WHERE qc.c_id = $courseId AND exercise_id = {$exercise->id} ";
  851. if (!empty($order)) {
  852. $order = Database::escape_string($order);
  853. $sql .= "ORDER BY $order";
  854. }
  855. $categories = [];
  856. $result = Database::query($sql);
  857. if (Database::num_rows($result)) {
  858. while ($row = Database::fetch_array($result, 'ASSOC')) {
  859. if ($excludeCategoryWithNoQuestions) {
  860. if ($row['count_questions'] == 0) {
  861. continue;
  862. }
  863. }
  864. if (empty($row['title']) && empty($row['category_id'])) {
  865. $row['title'] = get_lang('NoCategory');
  866. }
  867. $categories[$row['category_id']] = $row;
  868. }
  869. }
  870. if ($shuffle) {
  871. shuffle_assoc($categories);
  872. }
  873. return $categories;
  874. }
  875. /**
  876. * @param FormValidator $form
  877. * @param string $action
  878. */
  879. public function getForm(&$form, $action = 'new')
  880. {
  881. switch ($action) {
  882. case 'new':
  883. $header = get_lang('AddACategory');
  884. $submit = get_lang('AddTestCategory');
  885. break;
  886. case 'edit':
  887. $header = get_lang('EditCategory');
  888. $submit = get_lang('ModifyCategory');
  889. break;
  890. }
  891. // Setting the form elements
  892. $form->addElement('header', $header);
  893. $form->addElement('hidden', 'category_id');
  894. $form->addElement(
  895. 'text',
  896. 'category_name',
  897. get_lang('CategoryName'),
  898. ['class' => 'span6']
  899. );
  900. $form->add_html_editor(
  901. 'category_description',
  902. get_lang('CategoryDescription'),
  903. false,
  904. false,
  905. [
  906. 'ToolbarSet' => 'test_category',
  907. 'Width' => '90%',
  908. 'Height' => '200',
  909. ]
  910. );
  911. $category_parent_list = [];
  912. $options = [
  913. '1' => get_lang('Visible'),
  914. '0' => get_lang('Hidden'),
  915. ];
  916. $form->addElement(
  917. 'select',
  918. 'visibility',
  919. get_lang('Visibility'),
  920. $options
  921. );
  922. $script = null;
  923. if (!empty($this->parent_id)) {
  924. $parent_cat = new TestCategory();
  925. $parent_cat = $parent_cat->getCategory($this->parent_id);
  926. $category_parent_list = [$parent_cat->id => $parent_cat->name];
  927. $script .= '<script>$(function() { $("#parent_id").trigger("addItem",[{"title": "'.$parent_cat->name.'", "value": "'.$parent_cat->id.'"}]); });</script>';
  928. }
  929. $form->addElement('html', $script);
  930. $form->addElement('select', 'parent_id', get_lang('Parent'), $category_parent_list, ['id' => 'parent_id']);
  931. $form->addElement('style_submit_button', 'SubmitNote', $submit, 'class="add"');
  932. // setting the defaults
  933. $defaults = [];
  934. $defaults["category_id"] = $this->id;
  935. $defaults["category_name"] = $this->name;
  936. $defaults["category_description"] = $this->description;
  937. $defaults["parent_id"] = $this->parent_id;
  938. $defaults["visibility"] = $this->visibility;
  939. $form->setDefaults($defaults);
  940. // setting the rules
  941. $form->addRule('category_name', get_lang('ThisFieldIsRequired'), 'required');
  942. }
  943. /**
  944. * Returns the category form.
  945. *
  946. * @param Exercise $exercise
  947. *
  948. * @return string
  949. */
  950. public function returnCategoryForm(Exercise $exercise)
  951. {
  952. $categories = $this->getListOfCategoriesForTest($exercise);
  953. $saved_categories = $exercise->getCategoriesInExercise();
  954. $return = null;
  955. if (!empty($categories)) {
  956. $nbQuestionsTotal = $exercise->getNumberQuestionExerciseCategory();
  957. $exercise->setCategoriesGrouping(true);
  958. $real_question_count = count($exercise->getQuestionList());
  959. $warning = null;
  960. if ($nbQuestionsTotal != $real_question_count) {
  961. $warning = Display::return_message(
  962. get_lang('CheckThatYouHaveEnoughQuestionsInYourCategories'),
  963. 'warning'
  964. );
  965. }
  966. $return .= $warning;
  967. $return .= '<table class="data_table">';
  968. $return .= '<tr>';
  969. $return .= '<th height="24">'.get_lang('Categories').'</th>';
  970. $return .= '<th width="70" height="24">'.get_lang('Number').'</th></tr>';
  971. $emptyCategory = [
  972. 'id' => '0',
  973. 'name' => get_lang('NoCategory'),
  974. 'description' => '',
  975. 'iid' => '0',
  976. 'title' => get_lang('NoCategory'),
  977. ];
  978. $categories[] = $emptyCategory;
  979. foreach ($categories as $category) {
  980. $cat_id = $category['iid'];
  981. $return .= '<tr>';
  982. $return .= '<td>';
  983. $return .= Display::div($category['name']);
  984. $return .= '</td>';
  985. $return .= '<td>';
  986. $value = isset($saved_categories) && isset($saved_categories[$cat_id]) ? $saved_categories[$cat_id]['count_questions'] : -1;
  987. $return .= '<input name="category['.$cat_id.']" value="'.$value.'" />';
  988. $return .= '</td>';
  989. $return .= '</tr>';
  990. }
  991. $return .= '</table>';
  992. $return .= get_lang('ZeroMeansNoQuestionWillBeSelectedMinusOneMeansThatAllQuestionsWillBeSelected');
  993. }
  994. return $return;
  995. }
  996. /**
  997. * Sorts an array.
  998. *
  999. * @param array $array
  1000. *
  1001. * @return array
  1002. */
  1003. public function sort_tree_array($array)
  1004. {
  1005. foreach ($array as $key => $row) {
  1006. $parent[$key] = $row['parent_id'];
  1007. }
  1008. if (count($array) > 0) {
  1009. array_multisort($parent, SORT_ASC, $array);
  1010. }
  1011. return $array;
  1012. }
  1013. /**
  1014. * Return true if a category already exists with the same name.
  1015. *
  1016. * @param string $name
  1017. * @param int $courseId
  1018. *
  1019. * @return bool
  1020. */
  1021. public static function categoryTitleExists($name, $courseId = 0)
  1022. {
  1023. $categories = self::getCategoryListInfo('title', $courseId);
  1024. foreach ($categories as $title) {
  1025. if ($title == $name) {
  1026. return true;
  1027. }
  1028. }
  1029. return false;
  1030. }
  1031. /**
  1032. * Return the id of the test category with title = $in_title.
  1033. *
  1034. * @param string $title
  1035. * @param int $courseId
  1036. *
  1037. * @return int is id of test category
  1038. */
  1039. public static function get_category_id_for_title($title, $courseId = 0)
  1040. {
  1041. $out_res = 0;
  1042. if (empty($courseId)) {
  1043. $courseId = api_get_course_int_id();
  1044. }
  1045. $courseId = (int) $courseId;
  1046. $tbl_cat = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  1047. $sql = "SELECT id FROM $tbl_cat
  1048. WHERE c_id = $courseId AND title = '".Database::escape_string($title)."'";
  1049. $res = Database::query($sql);
  1050. if (Database::num_rows($res) > 0) {
  1051. $data = Database::fetch_array($res);
  1052. $out_res = $data['id'];
  1053. }
  1054. return $out_res;
  1055. }
  1056. /**
  1057. * Add a relation between question and category in table c_quiz_question_rel_category.
  1058. *
  1059. * @param int $categoryId
  1060. * @param int $questionId
  1061. * @param int $courseId
  1062. *
  1063. * @return string|false
  1064. */
  1065. public static function addCategoryToQuestion($categoryId, $questionId, $courseId)
  1066. {
  1067. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  1068. // if question doesn't have a category
  1069. // @todo change for 1.10 when a question can have several categories
  1070. if (self::getCategoryForQuestion($questionId, $courseId) == 0 &&
  1071. $questionId > 0 &&
  1072. $courseId > 0
  1073. ) {
  1074. $sql = "INSERT INTO $table (c_id, question_id, category_id)
  1075. VALUES (".intval($courseId).", ".intval($questionId).", ".intval($categoryId).")";
  1076. Database::query($sql);
  1077. $id = Database::insert_id();
  1078. return $id;
  1079. }
  1080. return false;
  1081. }
  1082. /**
  1083. * @param int $courseId
  1084. * @param int $sessionId
  1085. *
  1086. * @return array
  1087. */
  1088. public function getCategories($courseId, $sessionId = 0)
  1089. {
  1090. $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  1091. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1092. $sessionId = intval($sessionId);
  1093. $courseId = intval($courseId);
  1094. if (empty($sessionId)) {
  1095. $sessionCondition = api_get_session_condition(
  1096. $sessionId,
  1097. true,
  1098. false,
  1099. 'i.session_id'
  1100. );
  1101. } else {
  1102. $sessionCondition = api_get_session_condition(
  1103. $sessionId,
  1104. true,
  1105. true,
  1106. 'i.session_id'
  1107. );
  1108. }
  1109. if (empty($courseId)) {
  1110. return [];
  1111. }
  1112. $sql = "SELECT c.* FROM $table c
  1113. INNER JOIN $itemProperty i
  1114. ON c.c_id = i.c_id AND i.ref = c.id
  1115. WHERE
  1116. c.c_id = $courseId AND
  1117. i.tool = '".TOOL_TEST_CATEGORY."'
  1118. $sessionCondition
  1119. ORDER BY title";
  1120. $result = Database::query($sql);
  1121. return Database::store_result($result, 'ASSOC');
  1122. }
  1123. /**
  1124. * @param int $courseId
  1125. * @param int $sessionId
  1126. *
  1127. * @return string
  1128. */
  1129. public function displayCategories($courseId, $sessionId = 0)
  1130. {
  1131. $sessionId = (int) $sessionId;
  1132. $categories = $this->getCategories($courseId, $sessionId);
  1133. $html = '';
  1134. foreach ($categories as $category) {
  1135. $tmpobj = new TestCategory();
  1136. $tmpobj = $tmpobj->getCategory($category['id']);
  1137. $nb_question = $tmpobj->getCategoryQuestionsNumber();
  1138. $rowname = self::protectJSDialogQuote($category['title']);
  1139. $nb_question_label = $nb_question == 1 ? $nb_question.' '.get_lang('Question') : $nb_question.' '.get_lang('Questions');
  1140. $content = "<span style='float:right'>".$nb_question_label."</span>";
  1141. $content .= '<div class="sectioncomment">';
  1142. $content .= $category['description'];
  1143. $content .= '</div>';
  1144. $links = '';
  1145. if (!$sessionId) {
  1146. $links .= '<a href="'.api_get_self().'?action=editcategory&category_id='.$category['id'].'&'.api_get_cidreq().'">'.
  1147. Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>';
  1148. $links .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=deletecategory&category_id='.$category['id'].'" ';
  1149. $links .= 'onclick="return confirmDelete(\''.self::protectJSDialogQuote(get_lang('DeleteCategoryAreYouSure').'['.$rowname).'] ?\', \'id_cat'.$category['id'].'\');">';
  1150. $links .= Display::return_icon('delete.png', get_lang('Delete'), [], ICON_SIZE_SMALL).'</a>';
  1151. }
  1152. $html .= Display::panel($content, $category['title'].$links);
  1153. }
  1154. return $html;
  1155. }
  1156. /**
  1157. * To allowed " in javascript dialog box without bad surprises
  1158. * replace " with two '.
  1159. *
  1160. * @param string $text
  1161. *
  1162. * @return mixed
  1163. */
  1164. public function protectJSDialogQuote($text)
  1165. {
  1166. $res = $text;
  1167. $res = str_replace("'", "\'", $res);
  1168. // super astuce pour afficher les " dans les boite de dialogue
  1169. $res = str_replace('"', "\'\'", $res);
  1170. return $res;
  1171. }
  1172. }