auth.lib.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraField;
  4. /**
  5. * Class Auth
  6. * Auth can be used to instantiate objects or as a library to manage courses
  7. * This file contains a class used like library provides functions for auth tool.
  8. * It's also used like model to courses_controller (MVC pattern)
  9. * @author Christian Fasanando <christian1827@gmail.com>
  10. *
  11. * @package chamilo.auth
  12. */
  13. class Auth
  14. {
  15. /**
  16. * Constructor
  17. */
  18. public function __construct()
  19. {
  20. }
  21. /**
  22. * retrieves all the courses that the user has already subscribed to
  23. * @param int $user_id
  24. * @return array an array containing all the information of the courses of the given user
  25. */
  26. public function get_courses_of_user($user_id)
  27. {
  28. $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
  29. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  30. $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_EXTRA_FIELD);
  31. $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  32. $extraFieldType = ExtraField::COURSE_FIELD_TYPE;
  33. // get course list auto-register
  34. $sql = "SELECT item_id FROM $TABLE_COURSE_FIELD_VALUE tcfv
  35. INNER JOIN $TABLE_COURSE_FIELD tcf
  36. ON tcfv.field_id = tcf.id
  37. WHERE
  38. tcf.extra_field_type = $extraFieldType AND
  39. tcf.variable = 'special_course' AND
  40. tcfv.value = 1
  41. ";
  42. $result = Database::query($sql);
  43. $special_course_list = array();
  44. if (Database::num_rows($result) > 0) {
  45. while ($result_row = Database::fetch_array($result)) {
  46. $special_course_list[] = '"' . $result_row['item_id'] . '"';
  47. }
  48. }
  49. $without_special_courses = '';
  50. if (!empty($special_course_list)) {
  51. $without_special_courses = ' AND course.id NOT IN (' . implode(',', $special_course_list) . ')';
  52. }
  53. // Secondly we select the courses that are in a category (user_course_cat<>0) and sort these according to the sort of the category
  54. $user_id = intval($user_id);
  55. $sql = "SELECT
  56. course.code k,
  57. course.visual_code vc,
  58. course.subscribe subscr,
  59. course.unsubscribe unsubscr,
  60. course.title i,
  61. course.tutor_name t,
  62. course.category_code cat,
  63. course.directory dir,
  64. course_rel_user.status status,
  65. course_rel_user.sort sort,
  66. course_rel_user.user_course_cat user_course_cat
  67. FROM $TABLECOURS course, $TABLECOURSUSER course_rel_user
  68. WHERE
  69. course.id = course_rel_user.c_id AND
  70. course_rel_user.relation_type<>" . COURSE_RELATION_TYPE_RRHH . " AND
  71. course_rel_user.user_id = '" . $user_id . "' $without_special_courses
  72. ORDER BY course_rel_user.sort ASC";
  73. $result = Database::query($sql);
  74. $courses = array();
  75. while ($row = Database::fetch_array($result)) {
  76. //we only need the database name of the course
  77. $courses[] = array(
  78. 'code' => $row['k'],
  79. 'visual_code' => $row['vc'],
  80. 'title' => $row['i'],
  81. 'directory' => $row['dir'],
  82. 'status' => $row['status'],
  83. 'tutor' => $row['t'],
  84. 'subscribe' => $row['subscr'],
  85. 'category' => $row['cat'],
  86. 'unsubscribe' => $row['unsubscr'],
  87. 'sort' => $row['sort'],
  88. 'user_course_category' => $row['user_course_cat']
  89. );
  90. }
  91. return $courses;
  92. }
  93. /**
  94. * retrieves the user defined course categories
  95. * @return array containing all the IDs of the user defined courses categories, sorted by the "sort" field
  96. */
  97. public function get_user_course_categories()
  98. {
  99. $user_id = api_get_user_id();
  100. $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  101. $sql = "SELECT * FROM " . $table_category . "
  102. WHERE user_id=$user_id
  103. ORDER BY sort ASC";
  104. $result = Database::query($sql);
  105. $output = array();
  106. while ($row = Database::fetch_array($result)) {
  107. $output[] = $row;
  108. }
  109. return $output;
  110. }
  111. /**
  112. * This function get all the courses in the particular user category;
  113. * @return string The name of the user defined course category
  114. */
  115. public function get_courses_in_category()
  116. {
  117. $user_id = api_get_user_id();
  118. // table definitions
  119. $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
  120. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  121. $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_EXTRA_FIELD);
  122. $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  123. $extraFieldType = ExtraField::COURSE_FIELD_TYPE;
  124. // get course list auto-register
  125. $sql = "SELECT item_id
  126. FROM $TABLE_COURSE_FIELD_VALUE tcfv
  127. INNER JOIN $TABLE_COURSE_FIELD tcf
  128. ON tcfv.field_id = tcf.id
  129. WHERE
  130. tcf.extra_field_type = $extraFieldType AND
  131. tcf.variable = 'special_course' AND
  132. tcfv.value = 1 ";
  133. $result = Database::query($sql);
  134. $special_course_list = array();
  135. if (Database::num_rows($result) > 0) {
  136. while ($result_row = Database::fetch_array($result)) {
  137. $special_course_list[] = '"' . $result_row['item_id'] . '"';
  138. }
  139. }
  140. $without_special_courses = '';
  141. if (!empty($special_course_list)) {
  142. $without_special_courses = ' AND course.id NOT IN (' . implode(',', $special_course_list) . ')';
  143. }
  144. $sql = "SELECT
  145. course.code, course.visual_code, course.subscribe subscr, course.unsubscribe unsubscr,
  146. course.title title, course.tutor_name tutor, course.directory, course_rel_user.status status,
  147. course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
  148. FROM $TABLECOURS course,
  149. $TABLECOURSUSER course_rel_user
  150. WHERE
  151. course.id = course_rel_user.c_id AND
  152. course_rel_user.user_id = '" . $user_id . "' AND
  153. course_rel_user.relation_type <> " . COURSE_RELATION_TYPE_RRHH . "
  154. $without_special_courses
  155. ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
  156. $result = Database::query($sql);
  157. $data = array();
  158. while ($course = Database::fetch_array($result)) {
  159. $data[$course['user_course_cat']][] = $course;
  160. }
  161. return $data;
  162. }
  163. /**
  164. * stores the changes in a course category
  165. * (moving a course to a different course category)
  166. * @param int $courseId
  167. * @param int Category id
  168. * @return bool True if it success
  169. */
  170. public function updateCourseCategory($courseId, $newcategory)
  171. {
  172. $courseId = intval($courseId);
  173. $newcategory = intval($newcategory);
  174. $current_user = api_get_user_id();
  175. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  176. $max_sort_value = api_max_sort_value($newcategory, $current_user);
  177. $sql = "UPDATE $TABLECOURSUSER SET
  178. user_course_cat='" . $newcategory . "',
  179. sort='" . ($max_sort_value + 1) . "'
  180. WHERE
  181. c_id ='" . $courseId . "' AND
  182. user_id='" . $current_user . "' AND
  183. relation_type<>" . COURSE_RELATION_TYPE_RRHH;
  184. $resultQuery = Database::query($sql);
  185. $result = false;
  186. if (Database::affected_rows($resultQuery)) {
  187. $result = true;
  188. }
  189. return $result;
  190. }
  191. /**
  192. * moves the course one place up or down
  193. * @param string Direction (up/down)
  194. * @param string Course code
  195. * @param int Category id
  196. * @return bool True if it success
  197. */
  198. public function move_course($direction, $course2move, $category)
  199. {
  200. // definition of tables
  201. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  202. $current_user_id = api_get_user_id();
  203. $all_user_courses = $this->get_courses_of_user($current_user_id);
  204. // we need only the courses of the category we are moving in
  205. $user_courses = array();
  206. foreach ($all_user_courses as $key => $course) {
  207. if ($course['user_course_category'] == $category) {
  208. $user_courses[] = $course;
  209. }
  210. }
  211. $target_course = array();
  212. foreach ($user_courses as $count => $course) {
  213. if ($course2move == $course['code']) {
  214. // source_course is the course where we clicked the up or down icon
  215. $source_course = $course;
  216. // target_course is the course before/after the source_course (depending on the up/down icon)
  217. if ($direction == 'up') {
  218. $target_course = $user_courses[$count - 1];
  219. } else {
  220. $target_course = $user_courses[$count + 1];
  221. }
  222. break;
  223. }
  224. }
  225. $result = false;
  226. if (count($target_course) > 0 && count($source_course) > 0) {
  227. $courseInfo = api_get_course_info($source_course['code']);
  228. $courseId = $courseInfo['real_id'];
  229. $targetCourseInfo = api_get_course_info($target_course['code']);
  230. $targetCourseId = $targetCourseInfo['real_id'];
  231. $sql = "UPDATE $table
  232. SET sort='" . $target_course['sort'] . "'
  233. WHERE
  234. c_id = '" . $courseId . "' AND
  235. user_id = '" . $current_user_id . "' AND
  236. relation_type<>" . COURSE_RELATION_TYPE_RRHH;
  237. $result1 = Database::query($sql);
  238. $sql = "UPDATE $table SET sort='" . $source_course['sort'] . "'
  239. WHERE
  240. c_id ='" . $targetCourseId . "' AND
  241. user_id='" . $current_user_id . "' AND
  242. relation_type<>" . COURSE_RELATION_TYPE_RRHH;
  243. $result2 = Database::query($sql);
  244. if (Database::affected_rows($result1) && Database::affected_rows($result2)) {
  245. $result = true;
  246. }
  247. }
  248. return $result;
  249. }
  250. /**
  251. * Moves the course one place up or down
  252. * @param string Direction up/down
  253. * @param string Category id
  254. * @return bool True If it success
  255. */
  256. public function move_category($direction, $category2move)
  257. {
  258. // the database definition of the table that stores the user defined course categories
  259. $table_user_defined_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  260. $current_user_id = api_get_user_id();
  261. $user_coursecategories = $this->get_user_course_categories();
  262. $user_course_categories_info = $this->get_user_course_categories_info();
  263. $result = false;
  264. foreach ($user_coursecategories as $key => $category) {
  265. $category_id = $category['id'];
  266. if ($category2move == $category_id) {
  267. // source_course is the course where we clicked the up or down icon
  268. $source_category = $user_course_categories_info[$category2move];
  269. // target_course is the course before/after the source_course (depending on the up/down icon)
  270. if ($direction == 'up') {
  271. $target_category = $user_course_categories_info[$user_coursecategories[$key - 1]['id']];
  272. } else {
  273. $target_category = $user_course_categories_info[$user_coursecategories[$key + 1]['id']];
  274. }
  275. }
  276. }
  277. if (count($target_category) > 0 && count($source_category) > 0) {
  278. $sql_update1 = "UPDATE $table_user_defined_category SET sort='" . Database::escape_string($target_category['sort']) . "'
  279. WHERE id='" . intval($source_category['id']) . "' AND user_id='" . $current_user_id . "'";
  280. $sql_update2 = "UPDATE $table_user_defined_category SET sort='" . Database::escape_string($source_category['sort']) . "'
  281. WHERE id='" . intval($target_category['id']) . "' AND user_id='" . $current_user_id . "'";
  282. $result1 = Database::query($sql_update2);
  283. $result2 = Database::query($sql_update1);
  284. if (Database::affected_rows($result1) && Database::affected_rows($result2)) {
  285. $result = true;
  286. }
  287. }
  288. return $result;
  289. }
  290. /**
  291. * Retrieves the user defined course categories and all the info that goes with it
  292. * @return array containing all the info of the user defined courses categories with the id as key of the array
  293. */
  294. public function get_user_course_categories_info()
  295. {
  296. $current_user_id = api_get_user_id();
  297. $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  298. $sql = "SELECT * FROM " . $table_category . "
  299. WHERE user_id='" . $current_user_id . "'
  300. ORDER BY sort ASC";
  301. $result = Database::query($sql);
  302. while ($row = Database::fetch_array($result)) {
  303. $output[$row['id']] = $row;
  304. }
  305. return $output;
  306. }
  307. /**
  308. * Updates the user course category in the chamilo_user database
  309. * @param string Category title
  310. * @param int Category id
  311. * @return bool True if it success
  312. */
  313. public function store_edit_course_category($title, $category_id)
  314. {
  315. // protect data
  316. $title = Database::escape_string($title);
  317. $category_id = intval($category_id);
  318. $result = false;
  319. $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  320. $sql = "UPDATE $tucc
  321. SET title='" . api_htmlentities($title, ENT_QUOTES, api_get_system_encoding()) . "'
  322. WHERE id='" . $category_id . "'";
  323. $resultQuery = Database::query($sql);
  324. if (Database::affected_rows($resultQuery)) {
  325. $result = true;
  326. }
  327. return $result;
  328. }
  329. /**
  330. * deletes a course category and moves all the courses that were in this category to main category
  331. * @param int Category id
  332. * @return bool True if it success
  333. */
  334. public function delete_course_category($category_id)
  335. {
  336. $current_user_id = api_get_user_id();
  337. $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  338. $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  339. $category_id = intval($category_id);
  340. $result = false;
  341. $sql = "DELETE FROM $tucc
  342. WHERE
  343. id='" . $category_id . "' AND
  344. user_id='" . $current_user_id . "'";
  345. $resultQuery = Database::query($sql);
  346. if (Database::affected_rows($resultQuery)) {
  347. $result = true;
  348. }
  349. $sql = "UPDATE $TABLECOURSUSER
  350. SET user_course_cat='0'
  351. WHERE
  352. user_course_cat='" . $category_id . "' AND
  353. user_id='" . $current_user_id . "' AND
  354. relation_type<>" . COURSE_RELATION_TYPE_RRHH . " ";
  355. Database::query($sql);
  356. return $result;
  357. }
  358. /**
  359. * Search the courses database for a course that matches the search term.
  360. * The search is done on the code, title and tutor field of the course table.
  361. * @param string $search_term The string that the user submitted, what we are looking for
  362. * @param array $limit
  363. * @param boolean $justVisible search only on visible courses in the catalogue
  364. * @return array An array containing a list of all the courses matching the the search term.
  365. */
  366. public function search_courses($search_term, $limit, $justVisible = false)
  367. {
  368. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  369. $extraFieldTable = Database :: get_main_table(TABLE_EXTRA_FIELD);
  370. $extraFieldValuesTable = Database :: get_main_table(TABLE_EXTRA_FIELD_VALUES);
  371. $limitFilter = CourseCategory::getLimitFilterFromArray($limit);
  372. // get course list auto-register
  373. $sql = "SELECT item_id
  374. FROM $extraFieldValuesTable tcfv
  375. INNER JOIN $extraFieldTable tcf ON tcfv.field_id = tcf.id
  376. WHERE
  377. tcf.variable = 'special_course' AND
  378. tcfv.value = 1 ";
  379. $special_course_result = Database::query($sql);
  380. if (Database::num_rows($special_course_result) > 0) {
  381. $special_course_list = array();
  382. while ($result_row = Database::fetch_array($special_course_result)) {
  383. $special_course_list[] = '"' . $result_row['item_id'] . '"';
  384. }
  385. }
  386. $without_special_courses = '';
  387. if (!empty($special_course_list)) {
  388. $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
  389. }
  390. $visibilityCondition = $justVisible ? CourseManager::getCourseVisibilitySQLCondition('course') : '';
  391. $search_term_safe = Database::escape_string($search_term);
  392. $sql_find = "SELECT * FROM $courseTable
  393. WHERE (
  394. code LIKE '%" . $search_term_safe . "%' OR
  395. title LIKE '%" . $search_term_safe . "%' OR
  396. tutor_name LIKE '%" . $search_term_safe . "%'
  397. )
  398. $without_special_courses
  399. $visibilityCondition
  400. ORDER BY title, visual_code ASC
  401. $limitFilter
  402. ";
  403. if (api_is_multiple_url_enabled()) {
  404. $url_access_id = api_get_current_access_url_id();
  405. if ($url_access_id != -1) {
  406. $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  407. $sql_find = "SELECT *
  408. FROM $courseTable as course
  409. INNER JOIN $tbl_url_rel_course as url_rel_course
  410. ON (url_rel_course.c_id = course.id)
  411. WHERE
  412. access_url_id = $url_access_id AND (
  413. code LIKE '%" . $search_term_safe . "%' OR
  414. title LIKE '%" . $search_term_safe . "%' OR
  415. tutor_name LIKE '%" . $search_term_safe . "%'
  416. )
  417. $without_special_courses
  418. $visibilityCondition
  419. ORDER BY title, visual_code ASC
  420. $limitFilter
  421. ";
  422. }
  423. }
  424. $result_find = Database::query($sql_find);
  425. $courses = array();
  426. while ($row = Database::fetch_array($result_find)) {
  427. $row['registration_code'] = !empty($row['registration_code']);
  428. $count_users = count(CourseManager::get_user_list_from_course_code($row['code']));
  429. $count_connections_last_month = Tracking::get_course_connections_count(
  430. $row['id'], 0, api_get_utc_datetime(time() - (30 * 86400))
  431. );
  432. $point_info = CourseManager::get_course_ranking($row['id'], 0);
  433. $courses[] = array(
  434. 'real_id' => $row['id'],
  435. 'point_info' => $point_info,
  436. 'code' => $row['code'],
  437. 'directory' => $row['directory'],
  438. 'visual_code' => $row['visual_code'],
  439. 'title' => $row['title'],
  440. 'tutor' => $row['tutor_name'],
  441. 'subscribe' => $row['subscribe'],
  442. 'unsubscribe' => $row['unsubscribe'],
  443. 'registration_code' => $row['registration_code'],
  444. 'creation_date' => $row['creation_date'],
  445. 'visibility' => $row['visibility'],
  446. 'count_users' => $count_users,
  447. 'count_connections' => $count_connections_last_month
  448. );
  449. }
  450. return $courses;
  451. }
  452. /**
  453. * unsubscribe the user from a given course
  454. * @param string $course_code
  455. * @return bool True if it success
  456. */
  457. public function remove_user_from_course($course_code)
  458. {
  459. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  460. // protect variables
  461. $current_user_id = api_get_user_id();
  462. $course_code = Database::escape_string($course_code);
  463. $result = true;
  464. $courseInfo = api_get_course_info($course_code);
  465. $courseId = $courseInfo['real_id'];
  466. // we check (once again) if the user is not course administrator
  467. // because the course administrator cannot unsubscribe himself
  468. // (s)he can only delete the course
  469. $sql = "SELECT * FROM $tbl_course_user
  470. WHERE
  471. user_id='" . $current_user_id . "' AND
  472. c_id ='" . $courseId . "' AND
  473. status='1' ";
  474. $result_check = Database::query($sql);
  475. $number_of_rows = Database::num_rows($result_check);
  476. if ($number_of_rows > 0) {
  477. $result = false;
  478. }
  479. CourseManager::unsubscribe_user($current_user_id, $course_code);
  480. return $result;
  481. }
  482. /**
  483. * stores the user course category in the chamilo_user database
  484. * @param string Category title
  485. * @return bool True if it success
  486. */
  487. public function store_course_category($category_title)
  488. {
  489. $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
  490. // protect data
  491. $current_user_id = api_get_user_id();
  492. $category_title = Database::escape_string($category_title);
  493. $result = false;
  494. // step 1: we determine the max value of the user defined course categories
  495. $sql = "SELECT sort FROM $tucc
  496. WHERE user_id='" . $current_user_id . "'
  497. ORDER BY sort DESC";
  498. $rs_sort = Database::query($sql);
  499. $maxsort = Database::fetch_array($rs_sort);
  500. $nextsort = $maxsort['sort'] + 1;
  501. // step 2: we check if there is already a category with this name, if not we store it, else we give an error.
  502. $sql = "SELECT * FROM $tucc
  503. WHERE
  504. user_id='" . $current_user_id . "' AND
  505. title='" . $category_title . "'
  506. ORDER BY sort DESC";
  507. $rs = Database::query($sql);
  508. if (Database::num_rows($rs) == 0) {
  509. $sql = "INSERT INTO $tucc (user_id, title,sort)
  510. VALUES ('" . $current_user_id . "', '" . api_htmlentities($category_title, ENT_QUOTES, api_get_system_encoding()) . "', '" . $nextsort . "')";
  511. $resultQuery = Database::query($sql);
  512. if (Database::affected_rows($resultQuery)) {
  513. $result = true;
  514. }
  515. } else {
  516. $result = false;
  517. }
  518. return $result;
  519. }
  520. /**
  521. * Counts the number of courses in a given course category
  522. * @param string $categoryCode Category code
  523. * @param $searchTerm
  524. * @return int Count of courses
  525. */
  526. public function count_courses_in_category($categoryCode, $searchTerm = '')
  527. {
  528. return CourseCategory::countCoursesInCategory($categoryCode, $searchTerm);
  529. }
  530. /**
  531. * get the browsing of the course categories (faculties)
  532. * @return array array containing a list with all the categories and subcategories(if needed)
  533. */
  534. public function browse_course_categories()
  535. {
  536. return CourseCategory::browseCourseCategories();
  537. }
  538. /**
  539. * Display all the courses in the given course category. I could have used a parameter here
  540. * @param string $categoryCode Category code
  541. * @param int $randomValue
  542. * @param array $limit will be used if $random_value is not set.
  543. * This array should contains 'start' and 'length' keys
  544. * @return array Courses data
  545. */
  546. public function browse_courses_in_category($categoryCode, $randomValue = null, $limit = array())
  547. {
  548. return CourseCategory::browseCoursesInCategory($categoryCode, $randomValue, $limit);
  549. }
  550. /**
  551. * Subscribe the user to a given course
  552. * @param string $course_code Course code
  553. * @return string Message about results
  554. */
  555. public function subscribe_user($course_code)
  556. {
  557. $user_id = api_get_user_id();
  558. $all_course_information = CourseManager::get_course_information($course_code);
  559. if (
  560. $all_course_information['registration_code'] == '' ||
  561. (
  562. isset($_POST['course_registration_code']) &&
  563. $_POST['course_registration_code'] == $all_course_information['registration_code']
  564. )
  565. ) {
  566. if (api_is_platform_admin()) {
  567. $status_user_in_new_course = COURSEMANAGER;
  568. } else {
  569. $status_user_in_new_course = null;
  570. }
  571. if (CourseManager::add_user_to_course($user_id, $course_code, $status_user_in_new_course)) {
  572. $send = api_get_course_setting('email_alert_to_teacher_on_new_user_in_course', $course_code);
  573. if ($send == 1) {
  574. CourseManager::email_to_tutor($user_id, $all_course_information['real_id'], $send_to_tutor_also = false);
  575. } else if ($send == 2) {
  576. CourseManager::email_to_tutor($user_id, $all_course_information['real_id'], $send_to_tutor_also = true);
  577. }
  578. $url = Display::url($all_course_information['title'], api_get_course_url($course_code));
  579. $message = sprintf(get_lang('EnrollToCourseXSuccessful'), $url);
  580. } else {
  581. $message = get_lang('ErrorContactPlatformAdmin');
  582. }
  583. return array('message' => $message);
  584. } else {
  585. if (isset($_POST['course_registration_code']) && $_POST['course_registration_code'] != $all_course_information['registration_code']) {
  586. return false;
  587. }
  588. $message = get_lang('CourseRequiresPassword') . '<br />';
  589. $message .= $all_course_information['title'].' ('.$all_course_information['visual_code'].') ';
  590. $action = api_get_path(WEB_CODE_PATH) . "auth/courses.php?action=subscribe_user_with_password&sec_token=" . $_SESSION['sec_token'];
  591. $form = new FormValidator('subscribe_user_with_password', 'post', $action);
  592. $form->addElement('hidden', 'sec_token', $_SESSION['sec_token']);
  593. $form->addElement('hidden', 'subscribe_user_with_password', $all_course_information['code']);
  594. $form->addElement('text', 'course_registration_code');
  595. $form->addButton('submit', get_lang('SubmitRegistrationCode'));
  596. $content = $form->returnForm();
  597. return array('message' => $message, 'content' => $content);
  598. }
  599. }
  600. /**
  601. * List the sessions
  602. * @param string $date (optional) The date of sessions
  603. * @param array $limit
  604. * @return array The session list
  605. */
  606. public function browseSessions($date = null, $limit = array())
  607. {
  608. $em = Database::getManager();
  609. $qb = $em->createQueryBuilder();
  610. $_sessions = $qb->select('s')->from('ChamiloCoreBundle:Session', 's');
  611. if (!empty($limit)) {
  612. $_sessions->setFirstResult($limit['start'])
  613. ->setMaxResults($limit['length']);
  614. }
  615. $_sessions->where(
  616. $qb->expr()->gt('s.nbrCourses', 0)
  617. );
  618. if (!is_null($date)) {
  619. $_sessions
  620. ->andWhere(
  621. $qb->expr()->orX(
  622. $qb->expr()->between(':date', 's.accessStartDate', 's.accessEndDate'),
  623. $qb->expr()->isNull('s.accessEndDate'),
  624. $qb->expr()->andX(
  625. $qb->expr()->isNull('s.accessStartDate'),
  626. $qb->expr()->isNotNull('s.accessEndDate'),
  627. $qb->expr()->gt('s.accessEndDate', ':date')
  628. )
  629. )
  630. )
  631. ->setParameter('date', $date);
  632. }
  633. return $_sessions->getQuery()->getResult();
  634. }
  635. /**
  636. * Return a COUNT from Session table
  637. * @param string $date in Y-m-d format
  638. * @return int
  639. */
  640. public function countSessions($date = null)
  641. {
  642. $count = 0;
  643. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  644. $date = Database::escape_string($date);
  645. $dateFilter = '';
  646. if (!empty($date)) {
  647. $dateFilter = <<<SQL
  648. AND ('$date' BETWEEN s.access_start_date AND s.access_end_date)
  649. OR (s.access_end_date IS NULL)
  650. OR (s.access_start_date IS NULL AND
  651. s.access_end_date IS NOT NULL AND s.access_end_date > '$date')
  652. SQL;
  653. }
  654. $sql = "SELECT COUNT(*) FROM $sessionTable s WHERE 1 = 1 $dateFilter";
  655. $res = Database::query($sql);
  656. if ($res !== false && Database::num_rows($res) > 0) {
  657. $count = current(Database::fetch_row($res));
  658. }
  659. return $count;
  660. }
  661. /**
  662. * Search sessions by the tags in their courses
  663. * @param string $termTag Term for search in tags
  664. * @param array $limit Limit info
  665. * @return array The sessions
  666. */
  667. public function browseSessionsByTags($termTag, array $limit)
  668. {
  669. $em = Database::getManager();
  670. $qb = $em->createQueryBuilder();
  671. $sessions = $qb->select('s')
  672. ->distinct(true)
  673. ->from('ChamiloCoreBundle:Session', 's')
  674. ->innerJoin(
  675. 'ChamiloCoreBundle:SessionRelCourse',
  676. 'src',
  677. \Doctrine\ORM\Query\Expr\Join::WITH,
  678. 's.id = src.session'
  679. )
  680. ->innerJoin(
  681. 'ChamiloCoreBundle:ExtraFieldRelTag',
  682. 'frt',
  683. \Doctrine\ORM\Query\Expr\Join::WITH,
  684. 'src.course = frt.itemId'
  685. )
  686. ->innerJoin(
  687. 'ChamiloCoreBundle:Tag',
  688. 't',
  689. \Doctrine\ORM\Query\Expr\Join::WITH,
  690. 'frt.tagId = t.id'
  691. )
  692. ->innerJoin(
  693. 'ChamiloCoreBundle:ExtraField',
  694. 'f',
  695. \Doctrine\ORM\Query\Expr\Join::WITH,
  696. 'frt.fieldId = f.id'
  697. )
  698. ->where(
  699. $qb->expr()->like('t.tag', ":tag")
  700. )
  701. ->andWhere(
  702. $qb->expr()->eq('f.extraFieldType', ExtraField::COURSE_FIELD_TYPE)
  703. )
  704. ->setFirstResult($limit['start'])
  705. ->setMaxResults($limit['length'])
  706. ->setParameter('tag', "$termTag%")
  707. ->getQuery()
  708. ->getResult();
  709. $sessionsToBrowse = [];
  710. foreach ($sessions as $session) {
  711. if ($session->getNbrCourses() === 0) {
  712. continue;
  713. }
  714. $sessionsToBrowse[] = $session;
  715. }
  716. return $sessionsToBrowse;
  717. }
  718. /**
  719. * Search sessions by searched term by session name
  720. * @param string $queryTerm Term for search
  721. * @param array $limit Limit info
  722. * @return array The sessions
  723. */
  724. public function browseSessionsBySearch($queryTerm, array $limit)
  725. {
  726. $sessionsToBrowse = [];
  727. $criteria = Doctrine\Common\Collections\Criteria::create()
  728. ->where(
  729. Doctrine\Common\Collections\Criteria::expr()->contains('name', $queryTerm)
  730. )
  731. ->setFirstResult($limit['start'])
  732. ->setMaxResults($limit['length']);
  733. $sessions = Database::getManager()
  734. ->getRepository('ChamiloCoreBundle:Session')
  735. ->matching($criteria);
  736. foreach ($sessions as $session) {
  737. if ($session->getNbrCourses() === 0) {
  738. continue;
  739. }
  740. $sessionsToBrowse[] = $session;
  741. }
  742. return $sessionsToBrowse;
  743. }
  744. }