auth.lib.php 32 KB

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