TestCategory.php 36 KB

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