courses_controller.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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 = CoursesAndSessionsCatalog::browseSessions($date, [], false, true);
  328. $sessions = CoursesAndSessionsCatalog::browseSessions($date, $limit);
  329. $pageTotal = ceil($countSessions / $limit['length']);
  330. // Do NOT show pagination if only one page or less
  331. $pagination = $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', $pagination);
  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. * @return array
  391. */
  392. public static function getLimitArray()
  393. {
  394. $pageCurrent = isset($_REQUEST['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
  395. $pageLength = isset($_REQUEST['pageLength']) ? (int) $_GET['pageLength'] : CoursesAndSessionsCatalog::PAGE_LENGTH;
  396. return [
  397. 'start' => ($pageCurrent - 1) * $pageLength,
  398. 'current' => $pageCurrent,
  399. 'length' => $pageLength,
  400. ];
  401. }
  402. /**
  403. * Get the formatted data for sessions block to be displayed on Session Catalog page.
  404. *
  405. * @param array $sessions The session list
  406. *
  407. * @return array
  408. */
  409. private function getFormattedSessionsBlock(array $sessions)
  410. {
  411. $extraFieldValue = new ExtraFieldValue('session');
  412. $userId = api_get_user_id();
  413. $sessionsBlocks = [];
  414. $entityManager = Database::getManager();
  415. $sessionRelCourseRepo = $entityManager->getRepository('ChamiloCoreBundle:SessionRelCourse');
  416. $extraFieldRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraField');
  417. $extraFieldRelTagRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldRelTag');
  418. $tagsField = $extraFieldRepo->findOneBy([
  419. 'extraFieldType' => Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE,
  420. 'variable' => 'tags',
  421. ]);
  422. /** @var \Chamilo\CoreBundle\Entity\Session $session */
  423. foreach ($sessions as $session) {
  424. $sessionDates = SessionManager::parseSessionDates([
  425. 'display_start_date' => $session->getDisplayStartDate(),
  426. 'display_end_date' => $session->getDisplayEndDate(),
  427. 'access_start_date' => $session->getAccessStartDate(),
  428. 'access_end_date' => $session->getAccessEndDate(),
  429. 'coach_access_start_date' => $session->getCoachAccessStartDate(),
  430. 'coach_access_end_date' => $session->getCoachAccessEndDate(),
  431. ]);
  432. $imageField = $extraFieldValue->get_values_by_handler_and_field_variable(
  433. $session->getId(),
  434. 'image'
  435. );
  436. $sessionCourseTags = [];
  437. if (!is_null($tagsField)) {
  438. $sessionRelCourses = $sessionRelCourseRepo->findBy([
  439. 'session' => $session,
  440. ]);
  441. /** @var SessionRelCourse $sessionRelCourse */
  442. foreach ($sessionRelCourses as $sessionRelCourse) {
  443. $courseTags = $extraFieldRelTagRepo->getTags(
  444. $tagsField,
  445. $sessionRelCourse->getCourse()->getId()
  446. );
  447. /** @var Tag $tag */
  448. foreach ($courseTags as $tag) {
  449. $sessionCourseTags[] = $tag->getTag();
  450. }
  451. }
  452. }
  453. if (!empty($sessionCourseTags)) {
  454. $sessionCourseTags = array_unique($sessionCourseTags);
  455. }
  456. /** @var SequenceRepository $repo */
  457. $repo = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource');
  458. $sequences = $repo->getRequirementsAndDependenciesWithinSequences(
  459. $session->getId(),
  460. SequenceResource::SESSION_TYPE
  461. );
  462. $hasRequirements = false;
  463. foreach ($sequences['sequences'] as $sequence) {
  464. if (count($sequence['requirements']) === 0) {
  465. continue;
  466. }
  467. $hasRequirements = true;
  468. break;
  469. }
  470. $cat = $session->getCategory();
  471. if (empty($cat)) {
  472. $cat = null;
  473. $catName = '';
  474. } else {
  475. $catName = $cat->getName();
  476. }
  477. $generalCoach = $session->getGeneralCoach();
  478. $coachId = $generalCoach ? $generalCoach->getId() : 0;
  479. $coachName = $generalCoach ? UserManager::formatUserFullName($session->getGeneralCoach()) : '';
  480. $actions = null;
  481. if (api_is_platform_admin()) {
  482. $actions = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$session->getId();
  483. }
  484. $plugin = \BuyCoursesPlugin::create();
  485. $isThisSessionOnSale = $plugin->getBuyCoursePluginPrice($session);
  486. $sessionsBlock = [
  487. 'id' => $session->getId(),
  488. 'name' => $session->getName(),
  489. 'image' => isset($imageField['value']) ? $imageField['value'] : null,
  490. 'nbr_courses' => $session->getNbrCourses(),
  491. 'nbr_users' => $session->getNbrUsers(),
  492. 'coach_id' => $coachId,
  493. 'coach_url' => $generalCoach
  494. ? api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$coachId
  495. : '',
  496. 'coach_name' => $coachName,
  497. 'coach_avatar' => UserManager::getUserPicture(
  498. $coachId,
  499. USER_IMAGE_SIZE_SMALL
  500. ),
  501. 'is_subscribed' => SessionManager::isUserSubscribedAsStudent(
  502. $session->getId(),
  503. $userId
  504. ),
  505. 'icon' => $this->getSessionIcon($session->getName()),
  506. 'date' => $sessionDates['display'],
  507. 'price' => !empty($isThisSessionOnSale['html']) ? $isThisSessionOnSale['html'] : '',
  508. 'subscribe_button' => isset($isThisSessionOnSale['buy_button']) ? $isThisSessionOnSale['buy_button'] : $this->getRegisteredInSessionButton(
  509. $session->getId(),
  510. $session->getName(),
  511. $hasRequirements
  512. ),
  513. 'show_description' => $session->getShowDescription(),
  514. 'description' => $session->getDescription(),
  515. 'category' => $catName,
  516. 'tags' => $sessionCourseTags,
  517. 'edit_actions' => $actions,
  518. 'duration' => SessionManager::getDayLeftInSession(
  519. ['id' => $session->getId(), 'duration' => $session->getDuration()],
  520. $userId
  521. ),
  522. ];
  523. $sessionsBlock = array_merge($sessionsBlock, $sequences);
  524. $sessionsBlocks[] = $sessionsBlock;
  525. }
  526. return $sessionsBlocks;
  527. }
  528. }