TestCategory.php 39 KB

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