testcategory.class.php 41 KB

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