course_category.lib.php 36 KB

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