TestCategory.php 36 KB

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