courses_controller.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\SequenceRepository;
  4. use Chamilo\CoreBundle\Entity\SequenceResource;
  5. use Chamilo\CoreBundle\Entity\SessionRelCourse;
  6. use Chamilo\CoreBundle\Entity\Tag;
  7. /**
  8. * Class CoursesController.
  9. *
  10. * This file contains class used like controller,
  11. * it should be included inside a dispatcher file (e.g: index.php)
  12. *
  13. * @author Christian Fasanando <christian1827@gmail.com> - BeezNest
  14. *
  15. * @package chamilo.auth
  16. */
  17. class CoursesController
  18. {
  19. private $toolname;
  20. private $view;
  21. private $model;
  22. /**
  23. * Constructor.
  24. */
  25. public function __construct()
  26. {
  27. $this->toolname = 'auth';
  28. //$actived_theme_path = api_get_template();
  29. $this->view = new View($this->toolname);
  30. $this->model = new Auth();
  31. }
  32. /**
  33. * It's used for listing courses with categories,
  34. * render to courses_categories view.
  35. *
  36. * @param string $action
  37. * @param string $category_code
  38. * @param string $message
  39. * @param string $error
  40. * @param string $content
  41. * @param array $limit will be used if $random_value is not set.
  42. * This array should contains 'start' and 'length' keys
  43. *
  44. * @internal param \action $string
  45. * @internal param \Category $string code (optional)
  46. */
  47. public function courses_categories(
  48. $action,
  49. $category_code = null,
  50. $message = '',
  51. $error = '',
  52. $content = null,
  53. $limit = []
  54. ) {
  55. $data = [];
  56. $listCategories = CoursesAndSessionsCatalog::getCourseCategoriesTree();
  57. $data['countCoursesInCategory'] = CourseCategory::countCoursesInCategory($category_code);
  58. if ($action === 'display_random_courses') {
  59. // Random value is used instead limit filter
  60. $data['browse_courses_in_category'] = CoursesAndSessionsCatalog::getCoursesInCategory(null, 12);
  61. $data['countCoursesInCategory'] = count($data['browse_courses_in_category']);
  62. } else {
  63. if (!isset($category_code)) {
  64. $category_code = $listCategories['ALL']['code']; // by default first category
  65. }
  66. $limit = isset($limit) ? $limit : self::getLimitArray();
  67. $listCourses = CoursesAndSessionsCatalog::getCoursesInCategory($category_code, null, $limit);
  68. $data['browse_courses_in_category'] = $listCourses;
  69. }
  70. $data['list_categories'] = $listCategories;
  71. $data['code'] = Security::remove_XSS($category_code);
  72. // getting all the courses to which the user is subscribed to
  73. $curr_user_id = api_get_user_id();
  74. $user_courses = $this->model->get_courses_of_user($curr_user_id);
  75. $user_coursecodes = [];
  76. // we need only the course codes as these will be used to match against the courses of the category
  77. if ($user_courses != '') {
  78. foreach ($user_courses as $key => $value) {
  79. $user_coursecodes[] = $value['code'];
  80. }
  81. }
  82. if (api_is_drh()) {
  83. $courses = CourseManager::get_courses_followed_by_drh(api_get_user_id());
  84. foreach ($courses as $course) {
  85. $user_coursecodes[] = $course['code'];
  86. }
  87. }
  88. $data['user_coursecodes'] = $user_coursecodes;
  89. $data['action'] = $action;
  90. $data['message'] = $message;
  91. $data['content'] = $content;
  92. $data['error'] = $error;
  93. $data['catalogShowCoursesSessions'] = 0;
  94. $showCoursesSessions = (int) api_get_setting('catalog_show_courses_sessions');
  95. if ($showCoursesSessions > 0) {
  96. $data['catalogShowCoursesSessions'] = $showCoursesSessions;
  97. }
  98. // render to the view
  99. $this->view->set_data($data);
  100. $this->view->set_layout('layout');
  101. $this->view->set_template('courses_categories');
  102. $this->view->render();
  103. }
  104. /**
  105. * @param string $search_term
  106. * @param string $message
  107. * @param string $error
  108. * @param string $content
  109. * @param array $limit
  110. * @param bool $justVisible Whether to search only in courses visibles in the catalogue
  111. */
  112. public function search_courses(
  113. $search_term,
  114. $message = '',
  115. $error = '',
  116. $content = null,
  117. $limit = [],
  118. $justVisible = false
  119. ) {
  120. $data = [];
  121. $limit = !empty($limit) ? $limit : self::getLimitArray();
  122. $browse_course_categories = CoursesAndSessionsCatalog::getCourseCategories();
  123. $data['countCoursesInCategory'] = CourseCategory::countCoursesInCategory('ALL', $search_term);
  124. $data['browse_courses_in_category'] = CoursesAndSessionsCatalog::search_courses(
  125. $search_term,
  126. $limit,
  127. $justVisible
  128. );
  129. $data['browse_course_categories'] = $browse_course_categories;
  130. $data['search_term'] = Security::remove_XSS($search_term); //filter before showing in template
  131. // getting all the courses to which the user is subscribed to
  132. $curr_user_id = api_get_user_id();
  133. $user_courses = $this->model->get_courses_of_user($curr_user_id);
  134. $user_coursecodes = [];
  135. // we need only the course codes as these will be used to match against the courses of the category
  136. if ($user_courses != '') {
  137. foreach ($user_courses as $value) {
  138. $user_coursecodes[] = $value['code'];
  139. }
  140. }
  141. $data['user_coursecodes'] = $user_coursecodes;
  142. $data['message'] = $message;
  143. $data['content'] = $content;
  144. $data['error'] = $error;
  145. $data['action'] = 'display_courses';
  146. // render to the view
  147. $this->view->set_data($data);
  148. $this->view->set_layout('catalog_layout');
  149. $this->view->set_template('courses_categories');
  150. $this->view->render();
  151. }
  152. /**
  153. * Unsubscribe user from a course
  154. * render to listing view.
  155. *
  156. * @param string $course_code
  157. * @param string $search_term
  158. * @param string $category_code
  159. */
  160. public function unsubscribe_user_from_course(
  161. $course_code,
  162. $search_term = null,
  163. $category_code = null
  164. ) {
  165. $result = $this->model->remove_user_from_course($course_code);
  166. $message = '';
  167. $error = '';
  168. if ($result) {
  169. Display::addFlash(
  170. Display::return_message(get_lang('YouAreNowUnsubscribed'))
  171. );
  172. }
  173. if (!empty($search_term)) {
  174. CoursesAndSessionsCatalog::search_courses($search_term, $message, $error);
  175. } else {
  176. $this->courses_categories(
  177. 'subcribe',
  178. $category_code,
  179. $message,
  180. $error
  181. );
  182. }
  183. }
  184. /**
  185. * Get a HTML button for subscribe to session.
  186. *
  187. * @param int $sessionId The session ID
  188. * @param string $sessionName The session name
  189. * @param bool $checkRequirements Optional.
  190. * Whether the session has requirement. Default is false
  191. * @param bool $includeText Optional. Whether show the text in button
  192. * @param bool $btnBing
  193. *
  194. * @return string The button HTML
  195. */
  196. public function getRegisteredInSessionButton(
  197. $sessionId,
  198. $sessionName,
  199. $checkRequirements = false,
  200. $includeText = false,
  201. $btnBing = false
  202. ) {
  203. $sessionId = (int) $sessionId;
  204. if ($btnBing) {
  205. $btnBing = 'btn-lg btn-block';
  206. } else {
  207. $btnBing = 'btn-sm';
  208. }
  209. if ($checkRequirements) {
  210. $url = api_get_path(WEB_AJAX_PATH);
  211. $url .= 'sequence.ajax.php?';
  212. $url .= http_build_query([
  213. 'a' => 'get_requirements',
  214. 'id' => $sessionId,
  215. 'type' => SequenceResource::SESSION_TYPE,
  216. ]);
  217. return Display::toolbarButton(
  218. get_lang('CheckRequirements'),
  219. $url,
  220. 'shield',
  221. 'info',
  222. [
  223. 'class' => $btnBing.' ajax',
  224. 'data-title' => get_lang('CheckRequirements'),
  225. 'data-size' => 'md',
  226. 'title' => get_lang('CheckRequirements'),
  227. ],
  228. $includeText
  229. );
  230. }
  231. $catalogSessionAutoSubscriptionAllowed = false;
  232. if (api_get_setting('catalog_allow_session_auto_subscription') === 'true') {
  233. $catalogSessionAutoSubscriptionAllowed = true;
  234. }
  235. $url = api_get_path(WEB_CODE_PATH);
  236. if ($catalogSessionAutoSubscriptionAllowed) {
  237. $url .= 'auth/courses.php?';
  238. $url .= http_build_query([
  239. 'action' => 'subscribe_to_session',
  240. 'session_id' => $sessionId,
  241. ]);
  242. $result = Display::toolbarButton(
  243. get_lang('Subscribe'),
  244. $url,
  245. 'pencil',
  246. 'primary',
  247. [
  248. 'class' => $btnBing.' ajax',
  249. 'data-title' => get_lang('AreYouSureToSubscribe'),
  250. 'data-size' => 'md',
  251. 'title' => get_lang('Subscribe'),
  252. ],
  253. $includeText
  254. );
  255. } else {
  256. $url .= 'inc/email_editor.php?';
  257. $url .= http_build_query([
  258. 'action' => 'subscribe_me_to_session',
  259. 'session' => Security::remove_XSS($sessionName),
  260. ]);
  261. $result = Display::toolbarButton(
  262. get_lang('SubscribeToSessionRequest'),
  263. $url,
  264. 'pencil',
  265. 'primary',
  266. ['class' => $btnBing],
  267. $includeText
  268. );
  269. }
  270. $hook = HookResubscribe::create();
  271. if (!empty($hook)) {
  272. $hook->setEventData([
  273. 'session_id' => $sessionId,
  274. ]);
  275. try {
  276. $hook->notifyResubscribe(HOOK_EVENT_TYPE_PRE);
  277. } catch (Exception $exception) {
  278. $result = $exception->getMessage();
  279. }
  280. }
  281. return $result;
  282. }
  283. /**
  284. * Generate a label if the user has been registered in session.
  285. *
  286. * @return string The label
  287. */
  288. public function getAlreadyRegisteredInSessionLabel()
  289. {
  290. $icon = '<em class="fa fa-graduation-cap"></em>';
  291. return Display::div(
  292. $icon,
  293. [
  294. 'class' => 'btn btn-default btn-sm registered',
  295. 'title' => get_lang("AlreadyRegisteredToSession"),
  296. ]
  297. );
  298. }
  299. /**
  300. * Get a icon for a session.
  301. *
  302. * @param string $sessionName The session name
  303. *
  304. * @return string The icon
  305. */
  306. public function getSessionIcon($sessionName)
  307. {
  308. return Display::return_icon(
  309. 'window_list.png',
  310. $sessionName,
  311. null,
  312. ICON_SIZE_MEDIUM
  313. );
  314. }
  315. /**
  316. * Return Session catalog rendered view.
  317. *
  318. * @param string $action
  319. * @param string $nameTools
  320. * @param array $limit
  321. */
  322. public function sessionList($action, $nameTools, $limit = [])
  323. {
  324. $date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
  325. $hiddenLinks = isset($_GET['hidden_links']) ? $_GET['hidden_links'] == 1 : false;
  326. $limit = isset($limit) ? $limit : self::getLimitArray();
  327. $countSessions = SessionManager::countSessionsByEndDate($date);
  328. $sessions = CoursesAndSessionsCatalog::browseSessions($date, $limit);
  329. $pageTotal = ceil($countSessions / $limit['length']);
  330. // Do NOT show pagination if only one page or less
  331. $cataloguePagination = $pageTotal > 1 ? CourseCategory::getCatalogPagination($limit['current'], $limit['length'], $pageTotal) : '';
  332. $sessionsBlocks = $this->getFormattedSessionsBlock($sessions);
  333. // Get session search catalogue URL
  334. $courseUrl = CourseCategory::getCourseCategoryUrl(
  335. 1,
  336. $limit['length'],
  337. null,
  338. 0,
  339. 'subscribe'
  340. );
  341. $tpl = new Template();
  342. $tpl->assign('show_courses', CoursesAndSessionsCatalog::showCourses());
  343. $tpl->assign('show_sessions', CoursesAndSessionsCatalog::showSessions());
  344. $tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true');
  345. $tpl->assign('course_url', $courseUrl);
  346. $tpl->assign('catalog_pagination', $cataloguePagination);
  347. $tpl->assign('hidden_links', $hiddenLinks);
  348. $tpl->assign('search_token', Security::get_token());
  349. $tpl->assign('search_date', $date);
  350. $tpl->assign('web_session_courses_ajax_url', api_get_path(WEB_AJAX_PATH).'course.ajax.php');
  351. $tpl->assign('sessions', $sessionsBlocks);
  352. $tpl->assign('already_subscribed_label', $this->getAlreadyRegisteredInSessionLabel());
  353. $contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
  354. $tpl->display($contentTemplate);
  355. }
  356. /**
  357. * Show the Session Catalogue with filtered session by course tags.
  358. *
  359. * @param array $limit Limit info
  360. */
  361. public function sessionsListByCoursesTag(array $limit)
  362. {
  363. $searchTag = isset($_POST['search_tag']) ? $_POST['search_tag'] : null;
  364. $searchDate = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
  365. $hiddenLinks = isset($_GET['hidden_links']) ? intval($_GET['hidden_links']) == 1 : false;
  366. $courseUrl = CourseCategory::getCourseCategoryUrl(
  367. 1,
  368. $limit['length'],
  369. null,
  370. 0,
  371. 'subscribe'
  372. );
  373. $sessions = CoursesAndSessionsCatalog::browseSessionsByTags($searchTag, $limit);
  374. $sessionsBlocks = $this->getFormattedSessionsBlock($sessions);
  375. $tpl = new Template();
  376. $tpl->assign('show_courses', CoursesAndSessionsCatalog::showCourses());
  377. $tpl->assign('show_sessions', CoursesAndSessionsCatalog::showSessions());
  378. $tpl->assign('show_tutor', (api_get_setting('show_session_coach') === 'true' ? true : false));
  379. $tpl->assign('course_url', $courseUrl);
  380. $tpl->assign('already_subscribed_label', $this->getAlreadyRegisteredInSessionLabel());
  381. $tpl->assign('hidden_links', $hiddenLinks);
  382. $tpl->assign('search_token', Security::get_token());
  383. $tpl->assign('search_date', Security::remove_XSS($searchDate));
  384. $tpl->assign('search_tag', Security::remove_XSS($searchTag));
  385. $tpl->assign('sessions', $sessionsBlocks);
  386. $contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
  387. $tpl->display($contentTemplate);
  388. }
  389. /**
  390. * Show the Session Catalogue with filtered session by a query term.
  391. *
  392. * @param array $limit
  393. */
  394. public function sessionListBySearch(array $limit)
  395. {
  396. $q = isset($_REQUEST['q']) ? Security::remove_XSS($_REQUEST['q']) : null;
  397. $hiddenLinks = isset($_GET['hidden_links']) ? (int) $_GET['hidden_links'] == 1 : false;
  398. $courseUrl = CourseCategory::getCourseCategoryUrl(
  399. 1,
  400. $limit['length'],
  401. null,
  402. 0,
  403. 'subscribe'
  404. );
  405. $searchDate = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
  406. $sessions = CoursesAndSessionsCatalog::browseSessionsBySearch($q, $limit);
  407. $sessionsBlocks = $this->getFormattedSessionsBlock($sessions);
  408. $tpl = new Template();
  409. $tpl->assign('show_courses', CoursesAndSessionsCatalog::showCourses());
  410. $tpl->assign('show_sessions', CoursesAndSessionsCatalog::showSessions());
  411. $tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true' ? true : false);
  412. $tpl->assign('course_url', $courseUrl);
  413. $tpl->assign('already_subscribed_label', $this->getAlreadyRegisteredInSessionLabel());
  414. $tpl->assign('hidden_links', $hiddenLinks);
  415. $tpl->assign('search_token', Security::get_token());
  416. $tpl->assign('search_date', Security::remove_XSS($searchDate));
  417. $tpl->assign('search_tag', Security::remove_XSS($q));
  418. $tpl->assign('sessions', $sessionsBlocks);
  419. $contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
  420. $tpl->display($contentTemplate);
  421. }
  422. /**
  423. * @return array
  424. */
  425. public static function getLimitArray()
  426. {
  427. $pageCurrent = isset($_REQUEST['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
  428. $pageLength = isset($_REQUEST['pageLength']) ? (int) $_GET['pageLength'] : CoursesAndSessionsCatalog::PAGE_LENGTH;
  429. return [
  430. 'start' => ($pageCurrent - 1) * $pageLength,
  431. 'current' => $pageCurrent,
  432. 'length' => $pageLength,
  433. ];
  434. }
  435. /**
  436. * Get the formatted data for sessions block to be displayed on Session Catalog page.
  437. *
  438. * @param array $sessions The session list
  439. *
  440. * @return array
  441. */
  442. private function getFormattedSessionsBlock(array $sessions)
  443. {
  444. $extraFieldValue = new ExtraFieldValue('session');
  445. $userId = api_get_user_id();
  446. $sessionsBlocks = [];
  447. $entityManager = Database::getManager();
  448. $sessionRelCourseRepo = $entityManager->getRepository('ChamiloCoreBundle:SessionRelCourse');
  449. $extraFieldRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraField');
  450. $extraFieldRelTagRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldRelTag');
  451. $tagsField = $extraFieldRepo->findOneBy([
  452. 'extraFieldType' => Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE,
  453. 'variable' => 'tags',
  454. ]);
  455. /** @var \Chamilo\CoreBundle\Entity\Session $session */
  456. foreach ($sessions as $session) {
  457. $sessionDates = SessionManager::parseSessionDates([
  458. 'display_start_date' => $session->getDisplayStartDate(),
  459. 'display_end_date' => $session->getDisplayEndDate(),
  460. 'access_start_date' => $session->getAccessStartDate(),
  461. 'access_end_date' => $session->getAccessEndDate(),
  462. 'coach_access_start_date' => $session->getCoachAccessStartDate(),
  463. 'coach_access_end_date' => $session->getCoachAccessEndDate(),
  464. ]);
  465. $imageField = $extraFieldValue->get_values_by_handler_and_field_variable(
  466. $session->getId(),
  467. 'image'
  468. );
  469. $sessionCourseTags = [];
  470. if (!is_null($tagsField)) {
  471. $sessionRelCourses = $sessionRelCourseRepo->findBy([
  472. 'session' => $session,
  473. ]);
  474. /** @var SessionRelCourse $sessionRelCourse */
  475. foreach ($sessionRelCourses as $sessionRelCourse) {
  476. $courseTags = $extraFieldRelTagRepo->getTags(
  477. $tagsField,
  478. $sessionRelCourse->getCourse()->getId()
  479. );
  480. /** @var Tag $tag */
  481. foreach ($courseTags as $tag) {
  482. $sessionCourseTags[] = $tag->getTag();
  483. }
  484. }
  485. }
  486. if (!empty($sessionCourseTags)) {
  487. $sessionCourseTags = array_unique($sessionCourseTags);
  488. }
  489. /** @var SequenceRepository $repo */
  490. $repo = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource');
  491. $sequences = $repo->getRequirementsAndDependenciesWithinSequences(
  492. $session->getId(),
  493. SequenceResource::SESSION_TYPE
  494. );
  495. $hasRequirements = false;
  496. foreach ($sequences['sequences'] as $sequence) {
  497. if (count($sequence['requirements']) === 0) {
  498. continue;
  499. }
  500. $hasRequirements = true;
  501. break;
  502. }
  503. $cat = $session->getCategory();
  504. if (empty($cat)) {
  505. $cat = null;
  506. $catName = '';
  507. } else {
  508. $catName = $cat->getName();
  509. }
  510. $generalCoach = $session->getGeneralCoach();
  511. $coachId = $generalCoach ? $generalCoach->getId() : 0;
  512. $coachName = $generalCoach ? UserManager::formatUserFullName($session->getGeneralCoach()) : '';
  513. $actions = null;
  514. if (api_is_platform_admin()) {
  515. $actions = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$session->getId();
  516. }
  517. $plugin = \BuyCoursesPlugin::create();
  518. $isThisSessionOnSale = $plugin->getBuyCoursePluginPrice($session);
  519. $sessionsBlock = [
  520. 'id' => $session->getId(),
  521. 'name' => $session->getName(),
  522. 'image' => isset($imageField['value']) ? $imageField['value'] : null,
  523. 'nbr_courses' => $session->getNbrCourses(),
  524. 'nbr_users' => $session->getNbrUsers(),
  525. 'coach_id' => $coachId,
  526. 'coach_url' => $generalCoach
  527. ? api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$coachId
  528. : '',
  529. 'coach_name' => $coachName,
  530. 'coach_avatar' => UserManager::getUserPicture(
  531. $coachId,
  532. USER_IMAGE_SIZE_SMALL
  533. ),
  534. 'is_subscribed' => SessionManager::isUserSubscribedAsStudent(
  535. $session->getId(),
  536. $userId
  537. ),
  538. 'icon' => $this->getSessionIcon($session->getName()),
  539. 'date' => $sessionDates['display'],
  540. 'price' => !empty($isThisSessionOnSale['html']) ? $isThisSessionOnSale['html'] : '',
  541. 'subscribe_button' => isset($isThisSessionOnSale['buy_button']) ? $isThisSessionOnSale['buy_button'] : $this->getRegisteredInSessionButton(
  542. $session->getId(),
  543. $session->getName(),
  544. $hasRequirements
  545. ),
  546. 'show_description' => $session->getShowDescription(),
  547. 'description' => $session->getDescription(),
  548. 'category' => $catName,
  549. 'tags' => $sessionCourseTags,
  550. 'edit_actions' => $actions,
  551. 'duration' => SessionManager::getDayLeftInSession(
  552. ['id' => $session->getId(), 'duration' => $session->getDuration()],
  553. $userId
  554. ),
  555. ];
  556. $sessionsBlock = array_merge($sessionsBlock, $sequences);
  557. $sessionsBlocks[] = $sessionsBlock;
  558. }
  559. return $sessionsBlocks;
  560. }
  561. }