testcategory.class.php 33 KB

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