course_category.lib.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class CourseCategory
  5. */
  6. class CourseCategory
  7. {
  8. /**
  9. * Returns the category fields from the database from an int ID
  10. * @param int $categoryId The category ID
  11. * @return array
  12. */
  13. public static function getCategoryById($categoryId)
  14. {
  15. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  16. $categoryId = intval($categoryId);
  17. $sql = "SELECT * FROM $tbl_category WHERE id = $categoryId";
  18. $result = Database::query($sql);
  19. if (Database::num_rows($result)) {
  20. return Database::fetch_array($result, 'ASSOC');
  21. }
  22. return [];
  23. }
  24. /**
  25. * Get category details from a simple category code
  26. * @param string $category The literal category code
  27. * @return array
  28. */
  29. public static function getCategory($category)
  30. {
  31. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  32. $category = Database::escape_string($category);
  33. $sql = "SELECT * FROM $tbl_category WHERE code ='$category'";
  34. $result = Database::query($sql);
  35. if (Database::num_rows($result)) {
  36. return Database::fetch_array($result, 'ASSOC');
  37. }
  38. return [];
  39. }
  40. /**
  41. * @param string $category Optional. Parent category code
  42. * @return array
  43. */
  44. public static function getCategories($category = null)
  45. {
  46. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  47. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  48. $category = Database::escape_string($category);
  49. $conditions = null;
  50. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
  51. $conditions = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
  52. $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
  53. $parentIdCondition = " AND (t1.parent_id IS NULL OR t1.parent_id = '' )";
  54. if (!empty($category)) {
  55. $parentIdCondition = " AND t1.parent_id = '$category' ";
  56. }
  57. $sql = "SELECT
  58. t1.name,
  59. t1.code,
  60. t1.parent_id,
  61. t1.tree_pos,
  62. t1.children_count,
  63. COUNT(DISTINCT t3.code) AS nbr_courses
  64. FROM $tbl_category t1
  65. $conditions
  66. LEFT JOIN $tbl_category t2
  67. ON t1.code = t2.parent_id
  68. LEFT JOIN $tbl_course t3
  69. ON t3.category_code=t1.code
  70. WHERE
  71. 1 = 1
  72. $parentIdCondition
  73. $whereCondition
  74. GROUP BY t1.name,
  75. t1.code,
  76. t1.parent_id,
  77. t1.tree_pos,
  78. t1.children_count
  79. ORDER BY t1.tree_pos";
  80. $result = Database::query($sql);
  81. $categories = Database::store_result($result);
  82. return $categories;
  83. }
  84. /**
  85. * @param string $code
  86. * @param string $name
  87. * @param string $canHaveCourses
  88. * @param int $parent_id
  89. *
  90. * @return bool
  91. */
  92. public static function addNode($code, $name, $canHaveCourses, $parent_id)
  93. {
  94. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  95. $code = trim($code);
  96. $name = trim($name);
  97. $parent_id = trim($parent_id);
  98. $code = CourseManager::generate_course_code($code);
  99. $sql = "SELECT 1 FROM $tbl_category
  100. WHERE code = '".Database::escape_string($code)."'";
  101. $result = Database::query($sql);
  102. if (Database::num_rows($result)) {
  103. return false;
  104. }
  105. $result = Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $tbl_category");
  106. $row = Database::fetch_array($result);
  107. $tree_pos = $row['maxTreePos'] + 1;
  108. $params = [
  109. 'name' => $name,
  110. 'code' => $code,
  111. 'parent_id' => empty($parent_id) ? null : $parent_id,
  112. 'tree_pos' => $tree_pos,
  113. 'children_count' => 0,
  114. 'auth_course_child' => $canHaveCourses,
  115. 'auth_cat_child' => 'TRUE'
  116. ];
  117. $categoryId = Database::insert($tbl_category, $params);
  118. self::updateParentCategoryChildrenCount($parent_id, 1);
  119. self::addToUrl($categoryId);
  120. return $categoryId;
  121. }
  122. /**
  123. * Recursive function that updates the count of children in the parent
  124. * @param string $categoryId Category ID
  125. * @param int $delta The number to add or delete (1 to add one, -1 to remove one)
  126. */
  127. public static function updateParentCategoryChildrenCount($categoryId, $delta = 1)
  128. {
  129. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  130. $categoryId = Database::escape_string($categoryId);
  131. $delta = intval($delta);
  132. // First get to the highest level possible in the tree
  133. $result = Database::query("SELECT parent_id FROM $tbl_category WHERE code = '$categoryId'");
  134. $row = Database::fetch_array($result);
  135. if ($row !== false and $row['parent_id'] != 0) {
  136. // if a parent was found, enter there to see if he's got one more parent
  137. self::updateParentCategoryChildrenCount($row['parent_id'], $delta);
  138. }
  139. // Now we're at the top, get back down to update each child
  140. //$children_count = courseCategoryChildrenCount($categoryId);
  141. if ($delta >= 0) {
  142. $sql = "UPDATE $tbl_category SET children_count = (children_count + $delta)
  143. WHERE code = '$categoryId'";
  144. } else {
  145. $sql = "UPDATE $tbl_category SET children_count = (children_count - ".abs($delta).")
  146. WHERE code = '$categoryId'";
  147. }
  148. Database::query($sql);
  149. }
  150. /**
  151. * @param string $node
  152. */
  153. public static function deleteNode($node)
  154. {
  155. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  156. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  157. $node = Database::escape_string($node);
  158. $result = Database::query("SELECT parent_id, tree_pos FROM $tbl_category WHERE code='$node'");
  159. if ($row = Database::fetch_array($result)) {
  160. if (!empty($row['parent_id'])) {
  161. Database::query(
  162. "UPDATE $tbl_course SET category_code = '".$row['parent_id']."' WHERE category_code='$node'"
  163. );
  164. Database::query("UPDATE $tbl_category SET parent_id='".$row['parent_id']."' WHERE parent_id='$node'");
  165. } else {
  166. Database::query("UPDATE $tbl_course SET category_code='' WHERE category_code='$node'");
  167. Database::query("UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'");
  168. }
  169. Database::query("UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '".$row['tree_pos']."'");
  170. Database::query("DELETE FROM $tbl_category WHERE code='$node'");
  171. if (!empty($row['parent_id'])) {
  172. self::updateParentCategoryChildrenCount($row['parent_id'], -1);
  173. }
  174. }
  175. }
  176. /**
  177. * @param string $code
  178. * @param string $name
  179. * @param string $canHaveCourses
  180. * @param string $old_code
  181. * @return bool
  182. */
  183. public static function editNode($code, $name, $canHaveCourses, $old_code)
  184. {
  185. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  186. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  187. $code = trim(Database::escape_string($code));
  188. $name = trim(Database::escape_string($name));
  189. $old_code = Database::escape_string($old_code);
  190. $canHaveCourses = Database::escape_string($canHaveCourses);
  191. $code = CourseManager::generate_course_code($code);
  192. // Updating category
  193. $sql = "UPDATE $tbl_category SET
  194. name='$name',
  195. code='$code',
  196. auth_course_child = '$canHaveCourses'
  197. WHERE code = '$old_code'";
  198. Database::query($sql);
  199. // Updating children
  200. $sql = "UPDATE $tbl_category SET parent_id = '$code'
  201. WHERE parent_id = '$old_code'";
  202. Database::query($sql);
  203. // Updating course category
  204. $sql = "UPDATE $tbl_course SET category_code = '$code'
  205. WHERE category_code = '$old_code' ";
  206. Database::query($sql);
  207. return true;
  208. }
  209. /**
  210. * Move a node up on display
  211. * @param string $code
  212. * @param int $tree_pos
  213. * @param string $parent_id
  214. *
  215. * @return bool
  216. */
  217. public static function moveNodeUp($code, $tree_pos, $parent_id)
  218. {
  219. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  220. $code = Database::escape_string($code);
  221. $tree_pos = intval($tree_pos);
  222. $parent_id = Database::escape_string($parent_id);
  223. $parentIdCondition = " AND (parent_id IS NULL OR parent_id = '' )";
  224. if (!empty($parent_id)) {
  225. $parentIdCondition = " AND parent_id = '$parent_id' ";
  226. }
  227. $sql = "SELECT code,tree_pos
  228. FROM $tbl_category
  229. WHERE
  230. tree_pos < $tree_pos
  231. $parentIdCondition
  232. ORDER BY tree_pos DESC
  233. LIMIT 0,1";
  234. $result = Database::query($sql);
  235. if (!$row = Database::fetch_array($result)) {
  236. $sql = "SELECT code, tree_pos
  237. FROM $tbl_category
  238. WHERE
  239. tree_pos > $tree_pos
  240. $parentIdCondition
  241. ORDER BY tree_pos DESC
  242. LIMIT 0,1";
  243. $result2 = Database::query($sql);
  244. if (!$row = Database::fetch_array($result2)) {
  245. return false;
  246. }
  247. }
  248. $sql = "UPDATE $tbl_category
  249. SET tree_pos ='".$row['tree_pos']."'
  250. WHERE code='$code'";
  251. Database::query($sql);
  252. $sql = "UPDATE $tbl_category
  253. SET tree_pos = '$tree_pos'
  254. WHERE code= '".$row['code']."'";
  255. Database::query($sql);
  256. return true;
  257. }
  258. /**
  259. * Counts the number of children categories a category has
  260. * @param int $categoryId The ID of the category of which we want to count the children
  261. *
  262. * @return mixed The number of subcategories this category has
  263. */
  264. public static function courseCategoryChildrenCount($categoryId)
  265. {
  266. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  267. $categoryId = intval($categoryId);
  268. $count = 0;
  269. if (empty($categoryId)) {
  270. return 0;
  271. }
  272. $sql = "SELECT id, code FROM $tbl_category
  273. WHERE parent_id = $categoryId";
  274. $result = Database::query($sql);
  275. while ($row = Database::fetch_array($result)) {
  276. $count += self::courseCategoryChildrenCount($row['id']);
  277. }
  278. $sql = "UPDATE $tbl_category SET
  279. children_count = $count
  280. WHERE id = $categoryId";
  281. Database::query($sql);
  282. return $count + 1;
  283. }
  284. /**
  285. * @param string $categoryCode
  286. *
  287. * @return array
  288. */
  289. public static function getChildren($categoryCode)
  290. {
  291. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  292. $categoryCode = Database::escape_string($categoryCode);
  293. $sql = "SELECT code, id FROM $tbl_category
  294. WHERE parent_id = '$categoryCode'";
  295. $result = Database::query($sql);
  296. $children = [];
  297. while ($row = Database::fetch_array($result, 'ASSOC')) {
  298. $children[] = $row;
  299. $subChildren = self::getChildren($row['code']);
  300. $children = array_merge($children, $subChildren);
  301. }
  302. return $children;
  303. }
  304. /**
  305. * @param string $categoryCode
  306. *
  307. * @return array
  308. */
  309. public static function getParents($categoryCode)
  310. {
  311. if (empty($categoryCode)) {
  312. return [];
  313. }
  314. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  315. $categoryCode = Database::escape_string($categoryCode);
  316. $sql = "SELECT code, parent_id
  317. FROM $tbl_category
  318. WHERE code = '$categoryCode'";
  319. $result = Database::query($sql);
  320. $children = [];
  321. while ($row = Database::fetch_array($result, 'ASSOC')) {
  322. $parent = self::getCategory($row['parent_id']);
  323. $children[] = $row;
  324. $subChildren = self::getParents($parent ? $parent['code'] : null);
  325. $children = array_merge($children, $subChildren);
  326. }
  327. return $children;
  328. }
  329. /**
  330. * @param string $categoryCode
  331. * @return null|string
  332. */
  333. public static function getParentsToString($categoryCode)
  334. {
  335. $parents = self::getParents($categoryCode);
  336. if (!empty($parents)) {
  337. $parents = array_reverse($parents);
  338. $categories = [];
  339. foreach ($parents as $category) {
  340. $categories[] = $category['code'];
  341. }
  342. $categoriesInString = implode(' > ', $categories).' > ';
  343. return $categoriesInString;
  344. }
  345. return null;
  346. }
  347. /**
  348. * @param string $categorySource
  349. *
  350. * @return string
  351. */
  352. public static function listCategories($categorySource)
  353. {
  354. $categorySource = isset($categorySource) ? $categorySource : null;
  355. $categories = self::getCategories($categorySource);
  356. if (count($categories) > 0) {
  357. $table = new HTML_Table(array('class' => 'data_table'));
  358. $column = 0;
  359. $row = 0;
  360. $headers = array(
  361. get_lang('Category'),
  362. get_lang('SubCat'),
  363. get_lang('Courses'),
  364. get_lang('Actions')
  365. );
  366. foreach ($headers as $header) {
  367. $table->setHeaderContents($row, $column, $header);
  368. $column++;
  369. }
  370. $row++;
  371. $mainUrl = api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$categorySource;
  372. $editIcon = Display::return_icon(
  373. 'edit.png',
  374. get_lang('EditNode'),
  375. null,
  376. ICON_SIZE_SMALL
  377. );
  378. $deleteIcon = Display::return_icon(
  379. 'delete.png',
  380. get_lang('DeleteNode'),
  381. null,
  382. ICON_SIZE_SMALL
  383. );
  384. $moveIcon = Display::return_icon(
  385. 'up.png',
  386. get_lang('UpInSameLevel'),
  387. null,
  388. ICON_SIZE_SMALL
  389. );
  390. foreach ($categories as $category) {
  391. $editUrl = $mainUrl.'&id='.$category['code'].'&action=edit';
  392. $moveUrl = $mainUrl.'&id='.$category['code'].'&action=moveUp&tree_pos='.$category['tree_pos'];
  393. $deleteUrl = $mainUrl.'&id='.$category['code'].'&action=delete';
  394. $actions = Display::url($editIcon, $editUrl).
  395. Display::url($moveIcon, $moveUrl).
  396. Display::url($deleteIcon, $deleteUrl);
  397. $url = api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$category['code'];
  398. $title = Display::url(
  399. Display::return_icon(
  400. 'folder_document.png',
  401. get_lang('OpenNode'),
  402. null,
  403. ICON_SIZE_SMALL
  404. ).' '.$category['name'].' ('.$category['code'].')',
  405. $url
  406. );
  407. $content = array(
  408. $title,
  409. $category['children_count'],
  410. $category['nbr_courses'],
  411. $actions
  412. );
  413. $column = 0;
  414. foreach ($content as $value) {
  415. $table->setCellContents($row, $column, $value);
  416. $column++;
  417. }
  418. $row++;
  419. }
  420. return $table->toHtml();
  421. } else {
  422. return Display::return_message(get_lang('NoCategories'), 'warning');
  423. }
  424. }
  425. /**
  426. * @return array
  427. */
  428. public static function getCategoriesToDisplayInHomePage()
  429. {
  430. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  431. $sql = "SELECT name FROM $tbl_category
  432. WHERE parent_id IS NULL
  433. ORDER BY tree_pos";
  434. return Database::store_result(Database::query($sql));
  435. }
  436. /**
  437. * @param int $id
  438. *
  439. * @return bool
  440. */
  441. public static function addToUrl($id)
  442. {
  443. UrlManager::addCourseCategoryListToUrl(
  444. array($id),
  445. array(api_get_current_access_url_id())
  446. );
  447. }
  448. /**
  449. * @param string $categoryCode
  450. *
  451. * @return array
  452. */
  453. public static function getCategoriesCanBeAddedInCourse($categoryCode)
  454. {
  455. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
  456. $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
  457. $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
  458. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  459. $sql = "SELECT code, name
  460. FROM $tbl_category c
  461. $conditions
  462. WHERE (auth_course_child = 'TRUE' OR code = '".Database::escape_string($categoryCode)."')
  463. $whereCondition
  464. ORDER BY tree_pos";
  465. $res = Database::query($sql);
  466. $categories[''] = '-';
  467. while ($cat = Database::fetch_array($res)) {
  468. $categories[$cat['code']] = '('.$cat['code'].') '.$cat['name'];
  469. ksort($categories);
  470. }
  471. return $categories;
  472. }
  473. /**
  474. * @return array
  475. */
  476. public static function browseCourseCategories()
  477. {
  478. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  479. $conditions = null;
  480. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
  481. $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
  482. $whereCondition = " WHERE a.access_url_id = ".api_get_current_access_url_id();
  483. $sql = "SELECT c.* FROM $tbl_category c
  484. $conditions
  485. $whereCondition
  486. ORDER BY tree_pos ASC";
  487. $result = Database::query($sql);
  488. $url_access_id = 1;
  489. if (api_is_multiple_url_enabled()) {
  490. $url_access_id = api_get_current_access_url_id();
  491. }
  492. $countCourses = CourseManager::countAvailableCourses($url_access_id);
  493. $categories = [];
  494. $categories[0][0] = array(
  495. 'id' => 0,
  496. 'name' => get_lang('DisplayAll'),
  497. 'code' => 'ALL',
  498. 'parent_id' => null,
  499. 'tree_pos' => 0,
  500. 'count_courses' => $countCourses
  501. );
  502. while ($row = Database::fetch_array($result)) {
  503. $count_courses = self::countCoursesInCategory($row['code']);
  504. $row['count_courses'] = $count_courses;
  505. if (!isset($row['parent_id'])) {
  506. $categories[0][$row['tree_pos']] = $row;
  507. } else {
  508. $categories[$row['parent_id']][$row['tree_pos']] = $row;
  509. }
  510. }
  511. $count_courses = self::countCoursesInCategory();
  512. $categories[0][count($categories[0]) + 1] = array(
  513. 'id' => 0,
  514. 'name' => get_lang('None'),
  515. 'code' => 'NONE',
  516. 'parent_id' => null,
  517. 'tree_pos' => $row['tree_pos'] + 1,
  518. 'children_count' => 0,
  519. 'auth_course_child' => true,
  520. 'auth_cat_child' => true,
  521. 'count_courses' => $count_courses
  522. );
  523. return $categories;
  524. }
  525. /**
  526. * @param string $category_code
  527. * @param string $searchTerm
  528. * @return int
  529. */
  530. public static function countCoursesInCategory($category_code = '', $searchTerm = '')
  531. {
  532. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  533. $categoryCode = Database::escape_string($category_code);
  534. $searchTerm = Database::escape_string($searchTerm);
  535. $specialCourseList = CourseManager::get_special_course_list();
  536. $without_special_courses = '';
  537. if (!empty($specialCourseList)) {
  538. $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $specialCourseList).'")';
  539. }
  540. $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition(
  541. 'course',
  542. true
  543. );
  544. $categoryFilter = '';
  545. if ($categoryCode === 'ALL') {
  546. // Nothing to do
  547. } elseif ($categoryCode === 'NONE') {
  548. $categoryFilter = ' AND category_code = "" ';
  549. } else {
  550. $categoryFilter = ' AND category_code = "'.$categoryCode.'" ';
  551. }
  552. $searchFilter = '';
  553. if (!empty($searchTerm)) {
  554. $searchFilter = ' AND (code LIKE "%'.$searchTerm.'%"
  555. OR title LIKE "%'.$searchTerm.'%"
  556. OR tutor_name LIKE "%'.$searchTerm.'%") ';
  557. }
  558. $url_access_id = api_get_current_access_url_id();
  559. $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  560. $sql = "SELECT *
  561. FROM $tbl_course as course
  562. INNER JOIN $tbl_url_rel_course as url_rel_course
  563. ON (url_rel_course.c_id = course.id)
  564. WHERE
  565. access_url_id = $url_access_id AND
  566. course.visibility != '0' AND
  567. course.visibility != '4'
  568. $categoryFilter
  569. $searchFilter
  570. $without_special_courses
  571. $visibilityCondition
  572. ";
  573. return Database::num_rows(Database::query($sql));
  574. }
  575. /**
  576. * @param string $category_code
  577. * @param int $random_value
  578. * @param array $limit will be used if $random_value is not set.
  579. * This array should contains 'start' and 'length' keys
  580. * @return array
  581. */
  582. public static function browseCoursesInCategory($category_code, $random_value = null, $limit = [])
  583. {
  584. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  585. $specialCourseList = CourseManager::get_special_course_list();
  586. $without_special_courses = '';
  587. if (!empty($specialCourseList)) {
  588. $without_special_courses = ' AND course.id NOT IN ("'.implode('","', $specialCourseList).'")';
  589. }
  590. $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition(
  591. 'course',
  592. true
  593. );
  594. if (!empty($random_value)) {
  595. $random_value = intval($random_value);
  596. $sql = "SELECT COUNT(*) FROM $tbl_course";
  597. $result = Database::query($sql);
  598. list($num_records) = Database::fetch_row($result);
  599. if (api_is_multiple_url_enabled()) {
  600. $url_access_id = api_get_current_access_url_id();
  601. $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  602. $sql = "SELECT COUNT(*) FROM $tbl_course course
  603. INNER JOIN $tbl_url_rel_course as url_rel_course
  604. ON (url_rel_course.c_id = course.id)
  605. WHERE access_url_id = $url_access_id ";
  606. $result = Database::query($sql);
  607. list($num_records) = Database::fetch_row($result);
  608. $sql = "SELECT course.id FROM $tbl_course course
  609. INNER JOIN $tbl_url_rel_course as url_rel_course
  610. ON (url_rel_course.c_id = course.id)
  611. WHERE
  612. access_url_id = $url_access_id AND
  613. RAND()*$num_records< $random_value
  614. $without_special_courses
  615. $visibilityCondition
  616. ORDER BY RAND()
  617. LIMIT 0, $random_value";
  618. } else {
  619. $sql = "SELECT id FROM $tbl_course course
  620. WHERE
  621. RAND()*$num_records< $random_value
  622. $without_special_courses
  623. $visibilityCondition
  624. ORDER BY RAND()
  625. LIMIT 0, $random_value";
  626. }
  627. $result = Database::query($sql);
  628. $id_in = null;
  629. while (list($id) = Database::fetch_row($result)) {
  630. if ($id_in) {
  631. $id_in .= ",$id";
  632. } else {
  633. $id_in = "$id";
  634. }
  635. }
  636. if ($id_in === null) {
  637. return [];
  638. }
  639. $sql = "SELECT * FROM $tbl_course WHERE id IN($id_in)";
  640. } else {
  641. $limitFilter = self::getLimitFilterFromArray($limit);
  642. $category_code = Database::escape_string($category_code);
  643. if (empty($category_code) || $category_code == "ALL") {
  644. $sql = "SELECT * FROM $tbl_course
  645. WHERE
  646. 1=1
  647. $without_special_courses
  648. $visibilityCondition
  649. ORDER BY title $limitFilter ";
  650. } else {
  651. if ($category_code == 'NONE') {
  652. $category_code = '';
  653. }
  654. $sql = "SELECT * FROM $tbl_course
  655. WHERE
  656. category_code='$category_code'
  657. $without_special_courses
  658. $visibilityCondition
  659. ORDER BY title $limitFilter ";
  660. }
  661. // Showing only the courses of the current Chamilo access_url_id
  662. if (api_is_multiple_url_enabled()) {
  663. $url_access_id = api_get_current_access_url_id();
  664. $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  665. if ($category_code != "ALL") {
  666. $sql = "SELECT * FROM $tbl_course as course
  667. INNER JOIN $tbl_url_rel_course as url_rel_course
  668. ON (url_rel_course.c_id = course.id)
  669. WHERE
  670. access_url_id = $url_access_id AND
  671. category_code='$category_code'
  672. $without_special_courses
  673. $visibilityCondition
  674. ORDER BY title $limitFilter";
  675. } else {
  676. $sql = "SELECT * FROM $tbl_course as course
  677. INNER JOIN $tbl_url_rel_course as url_rel_course
  678. ON (url_rel_course.c_id = course.id)
  679. WHERE
  680. access_url_id = $url_access_id
  681. $without_special_courses
  682. $visibilityCondition
  683. ORDER BY title $limitFilter";
  684. }
  685. }
  686. }
  687. $result = Database::query($sql);
  688. $courses = [];
  689. while ($row = Database::fetch_array($result)) {
  690. $row['registration_code'] = !empty($row['registration_code']);
  691. $count_users = CourseManager::get_users_count_in_course($row['code']);
  692. $count_connections_last_month = Tracking::get_course_connections_count(
  693. $row['id'],
  694. 0,
  695. api_get_utc_datetime(time() - (30 * 86400))
  696. );
  697. if ($row['tutor_name'] == '0') {
  698. $row['tutor_name'] = get_lang('NoManager');
  699. }
  700. $point_info = CourseManager::get_course_ranking($row['id'], 0);
  701. $courses[] = array(
  702. 'real_id' => $row['id'],
  703. 'point_info' => $point_info,
  704. 'code' => $row['code'],
  705. 'directory' => $row['directory'],
  706. 'visual_code' => $row['visual_code'],
  707. 'title' => $row['title'],
  708. 'tutor' => $row['tutor_name'],
  709. 'subscribe' => $row['subscribe'],
  710. 'unsubscribe' => $row['unsubscribe'],
  711. 'registration_code' => $row['registration_code'],
  712. 'creation_date' => $row['creation_date'],
  713. 'visibility' => $row['visibility'],
  714. 'category' => $row['category_code'],
  715. 'count_users' => $count_users,
  716. 'count_connections' => $count_connections_last_month
  717. );
  718. }
  719. return $courses;
  720. }
  721. /**
  722. * create recursively all categories as option of the select passed in parameter.
  723. *
  724. * @param HTML_QuickForm_Element $element
  725. * @param string $defaultCode the option value to select by default (used mainly for edition of courses)
  726. * @param string $parentCode the parent category of the categories added (default=null for root category)
  727. * @param string $padding the indent param (you shouldn't indicate something here)
  728. */
  729. public static function setCategoriesInForm(
  730. $element,
  731. $defaultCode = null,
  732. $parentCode = null,
  733. $padding = null
  734. ) {
  735. $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
  736. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
  737. $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
  738. $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
  739. $sql = "SELECT code, name, auth_course_child, auth_cat_child
  740. FROM $tbl_category c
  741. $conditions
  742. WHERE parent_id ".(empty($parentCode) ? "IS NULL" : "='".Database::escape_string($parentCode)."'")."
  743. $whereCondition
  744. ORDER BY name, code";
  745. $res = Database::query($sql);
  746. while ($cat = Database::fetch_array($res, 'ASSOC')) {
  747. $params = $cat['auth_course_child'] == 'TRUE' ? '' : 'disabled';
  748. $params .= ($cat['code'] == $defaultCode) ? ' selected' : '';
  749. $option = $padding.' '.$cat['name'].' ('.$cat['code'].')';
  750. $element->addOption($option, $cat['code'], $params);
  751. if ($cat['auth_cat_child'] == 'TRUE') {
  752. self::setCategoriesInForm(
  753. $element,
  754. $defaultCode,
  755. $cat['code'],
  756. $padding.' - '
  757. );
  758. }
  759. }
  760. }
  761. /**
  762. * @param array $list
  763. * @return array
  764. */
  765. public static function getCourseCategoryNotInList($list)
  766. {
  767. $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  768. if (empty($list)) {
  769. $sql = "SELECT * FROM $table
  770. WHERE (parent_id IS NULL) ";
  771. $result = Database::query($sql);
  772. return Database::store_result($result, 'ASSOC');
  773. }
  774. $list = array_map('intval', $list);
  775. $listToString = implode("','", $list);
  776. $sql = "SELECT * FROM $table
  777. WHERE id NOT IN ('$listToString') AND (parent_id IS NULL) ";
  778. $result = Database::query($sql);
  779. return Database::store_result($result, 'ASSOC');
  780. }
  781. /**
  782. * @param string $keyword
  783. * @return array|null
  784. */
  785. public static function searchCategoryByKeyword($keyword)
  786. {
  787. if (empty($keyword)) {
  788. return null;
  789. }
  790. $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
  791. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
  792. $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
  793. $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
  794. $keyword = Database::escape_string($keyword);
  795. $sql = "SELECT c.*, c.name as text
  796. FROM $tableCategory c $conditions
  797. WHERE
  798. (
  799. c.code LIKE '%$keyword%' OR name LIKE '%$keyword%'
  800. ) AND auth_course_child = 'TRUE'
  801. $whereCondition ";
  802. $result = Database::query($sql);
  803. return Database::store_result($result, 'ASSOC');
  804. }
  805. /**
  806. * @param array $list
  807. * @return array
  808. */
  809. public static function searchCategoryById($list)
  810. {
  811. if (empty($list)) {
  812. return [];
  813. } else {
  814. $list = array_map('intval', $list);
  815. $list = implode("','", $list);
  816. }
  817. $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
  818. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
  819. $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
  820. $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
  821. $sql = "SELECT c.*, c.name as text FROM $tableCategory c $conditions
  822. WHERE c.id IN $list $whereCondition";
  823. $result = Database::query($sql);
  824. return Database::store_result($result, 'ASSOC');
  825. }
  826. /**
  827. * @return array
  828. */
  829. public static function getLimitArray()
  830. {
  831. $pageCurrent = isset($_REQUEST['pageCurrent']) ? intval($_GET['pageCurrent']) : 1;
  832. $pageLength = isset($_REQUEST['pageLength']) ? intval($_GET['pageLength']) : CoursesAndSessionsCatalog::PAGE_LENGTH;
  833. return array(
  834. 'start' => ($pageCurrent - 1) * $pageLength,
  835. 'current' => $pageCurrent,
  836. 'length' => $pageLength
  837. );
  838. }
  839. /**
  840. * Return LIMIT to filter SQL query
  841. * @param array $limit
  842. * @return string
  843. */
  844. public static function getLimitFilterFromArray($limit)
  845. {
  846. $limitFilter = '';
  847. if (!empty($limit) && is_array($limit)) {
  848. $limitStart = isset($limit['start']) ? $limit['start'] : 0;
  849. $limitLength = isset($limit['length']) ? $limit['length'] : 12;
  850. $limitFilter = 'LIMIT '.$limitStart.', '.$limitLength;
  851. }
  852. return $limitFilter;
  853. }
  854. /**
  855. * Get Pagination HTML div
  856. * @param $pageCurrent
  857. * @param $pageLength
  858. * @param $pageTotal
  859. * @return string
  860. */
  861. public static function getCatalogPagination($pageCurrent, $pageLength, $pageTotal)
  862. {
  863. // Start empty html
  864. $pageDiv = '';
  865. $html = '';
  866. $pageBottom = max(1, $pageCurrent - 3);
  867. $pageTop = min($pageTotal, $pageCurrent + 3);
  868. if ($pageBottom > 1) {
  869. $pageDiv .= self::getPageNumberItem(1, $pageLength);
  870. if ($pageBottom > 2) {
  871. $pageDiv .= self::getPageNumberItem(
  872. $pageBottom - 1,
  873. $pageLength,
  874. null,
  875. '...'
  876. );
  877. }
  878. }
  879. // For each page add its page button to html
  880. for ($i = $pageBottom; $i <= $pageTop; $i++) {
  881. if ($i === $pageCurrent) {
  882. $pageItemAttributes = array('class' => 'active');
  883. } else {
  884. $pageItemAttributes = [];
  885. }
  886. $pageDiv .= self::getPageNumberItem(
  887. $i,
  888. $pageLength,
  889. $pageItemAttributes
  890. );
  891. }
  892. // Check if current page is the last page
  893. if ($pageTop < $pageTotal) {
  894. if ($pageTop < ($pageTotal - 1)) {
  895. $pageDiv .= self::getPageNumberItem(
  896. $pageTop + 1,
  897. $pageLength,
  898. null,
  899. '...'
  900. );
  901. }
  902. $pageDiv .= self::getPageNumberItem($pageTotal, $pageLength);
  903. }
  904. // Complete pagination html
  905. $pageDiv = Display::tag('ul', $pageDiv, array('class' => 'pagination'));
  906. $html .= '<nav>'.$pageDiv.'</nav>';
  907. return $html;
  908. }
  909. /**
  910. * Return URL to course catalog
  911. * @param int $pageCurrent
  912. * @param int $pageLength
  913. * @param string $categoryCode
  914. * @param int $hiddenLinks
  915. * @param string $action
  916. * @return string
  917. */
  918. public static function getCourseCategoryUrl(
  919. $pageCurrent,
  920. $pageLength,
  921. $categoryCode = null,
  922. $hiddenLinks = null,
  923. $action = null
  924. ) {
  925. $requestAction = isset($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : null;
  926. $action = isset($action) ? Security::remove_XSS($action) : $requestAction;
  927. $searchTerm = isset($_REQUEST['search_term']) ? Security::remove_XSS($_REQUEST['search_term']) : null;
  928. if ($action === 'subscribe_user_with_password') {
  929. $action = 'subscribe';
  930. }
  931. $categoryCodeRequest = isset($_REQUEST['category_code']) ? Security::remove_XSS($_REQUEST['category_code']) : null;
  932. $categoryCode = isset($categoryCode) ? Security::remove_XSS($categoryCode) : $categoryCodeRequest;
  933. $hiddenLinksRequest = isset($_REQUEST['hidden_links']) ? Security::remove_XSS($_REQUEST['hidden_links']) : null;
  934. $hiddenLinks = isset($hiddenLinks) ? Security::remove_XSS($hiddenLinksRequest) : $categoryCodeRequest;
  935. // Start URL with params
  936. $pageUrl = api_get_self().
  937. '?action='.$action.
  938. '&category_code='.$categoryCode.
  939. '&hidden_links='.$hiddenLinks.
  940. '&pageCurrent='.$pageCurrent.
  941. '&pageLength='.$pageLength;
  942. switch ($action) {
  943. case 'subscribe':
  944. // for search
  945. $pageUrl .=
  946. '&search_term='.$searchTerm.
  947. '&search_course=1'.
  948. '&sec_token='.Security::getTokenFromSession();
  949. break;
  950. case 'display_courses':
  951. // No break
  952. default:
  953. break;
  954. }
  955. return $pageUrl;
  956. }
  957. /**
  958. * Get li HTML of page number
  959. * @param $pageNumber
  960. * @param $pageLength
  961. * @param array $liAttributes
  962. * @param string $content
  963. * @return string
  964. */
  965. public static function getPageNumberItem(
  966. $pageNumber,
  967. $pageLength,
  968. $liAttributes = [],
  969. $content = ''
  970. ) {
  971. // Get page URL
  972. $url = self::getCourseCategoryUrl(
  973. $pageNumber,
  974. $pageLength
  975. );
  976. // If is current page ('active' class) clear URL
  977. if (isset($liAttributes) && is_array($liAttributes) && isset($liAttributes['class'])) {
  978. if (strpos('active', $liAttributes['class']) !== false) {
  979. $url = '';
  980. }
  981. }
  982. $content = !empty($content) ? $content : $pageNumber;
  983. return Display::tag(
  984. 'li',
  985. Display::url(
  986. $content,
  987. $url
  988. ),
  989. $liAttributes
  990. );
  991. }
  992. /**
  993. * Return the name tool by action
  994. * @param string $action
  995. * @return string
  996. */
  997. public static function getCourseCatalogNameTools($action)
  998. {
  999. $nameTools = get_lang('SortMyCourses');
  1000. if (empty($action)) {
  1001. return $nameTools; //should never happen
  1002. }
  1003. switch ($action) {
  1004. case 'createcoursecategory':
  1005. $nameTools = get_lang('CreateCourseCategory');
  1006. break;
  1007. case 'subscribe':
  1008. $nameTools = get_lang('CourseManagement');
  1009. break;
  1010. case 'subscribe_user_with_password':
  1011. $nameTools = get_lang('CourseManagement');
  1012. break;
  1013. case 'display_random_courses':
  1014. // No break
  1015. case 'display_courses':
  1016. $nameTools = get_lang('CourseManagement');
  1017. break;
  1018. case 'display_sessions':
  1019. $nameTools = get_lang('Sessions');
  1020. break;
  1021. default:
  1022. // Nothing to do
  1023. break;
  1024. }
  1025. return $nameTools;
  1026. }
  1027. /**
  1028. * Save image for a course category
  1029. * @param int $categoryId Course category ID
  1030. * @param array $fileData File data from $_FILES
  1031. */
  1032. public static function saveImage($categoryId, $fileData)
  1033. {
  1034. $categoryInfo = self::getCategoryById($categoryId);
  1035. if (empty($categoryInfo)) {
  1036. return;
  1037. }
  1038. if (!empty($fileData['error'])) {
  1039. return;
  1040. }
  1041. $extension = getextension($fileData['name']);
  1042. $dirName = 'course_category/';
  1043. $fileDir = api_get_path(SYS_UPLOAD_PATH).$dirName;
  1044. $fileName = "cc_$categoryId.{$extension[0]}";
  1045. if (!file_exists($fileDir)) {
  1046. mkdir($fileDir, api_get_permissions_for_new_directories(), true);
  1047. }
  1048. $image = new Image($fileData['tmp_name']);
  1049. $image->send_image($fileDir.$fileName);
  1050. $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1051. Database::update(
  1052. $table,
  1053. ['image' => $dirName.$fileName],
  1054. ['id = ?' => $categoryId]
  1055. );
  1056. }
  1057. /**
  1058. * @param $categoryId
  1059. * @param string $description
  1060. *
  1061. * @return string
  1062. */
  1063. public static function saveDescription($categoryId, $description)
  1064. {
  1065. $categoryInfo = self::getCategoryById($categoryId);
  1066. if (empty($categoryInfo)) {
  1067. return false;
  1068. }
  1069. $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1070. Database::update(
  1071. $table,
  1072. ['description' => $description],
  1073. ['id = ?' => $categoryId]
  1074. );
  1075. return true;
  1076. }
  1077. }