Refactor course catalog, remove CoursesController BT#16815

pull/3147/head
Julio Montoya 6 years ago
parent 401672da81
commit ba458fedd4
  1. 22
      main/auth/catalog_layout.php
  2. 417
      main/auth/courses.php
  3. 523
      main/auth/courses_categories.php
  4. 684
      main/auth/courses_controller.php
  5. 4
      main/course_info/about.php
  6. 3
      main/inc/ajax/sequence.ajax.php
  7. 727
      main/inc/lib/CoursesAndSessionsCatalog.class.php
  8. 32
      main/inc/lib/auth.lib.php
  9. 6
      main/inc/lib/course.lib.php
  10. 34
      main/inc/lib/course_category.lib.php
  11. 2
      main/inc/lib/userportal.lib.php
  12. 4
      main/session/about.php
  13. 2
      main/template/default/layout/page.tpl
  14. 2
      main/template/default/layout/show_header.tpl

@ -1,22 +0,0 @@
<?php
/* For licensing terms, see /license.txt */
/**
* Layout (principal view) used for structuring course/session catalog.
*
* @author Angel Fernando Quiroz Campos <angel.quiroz@beeznest.com>
*
* @package chamilo.auth
*/
if (api_get_setting('course_catalog_published') !== 'true') {
// Access rights: anonymous users can't do anything usefull here.
api_block_anonymous_users();
}
// Header
Display::display_header('');
// Display
echo $content;
// Footer
Display::display_footer();

@ -4,21 +4,15 @@
use Chamilo\CoreBundle\Entity\SequenceResource;
/**
* Template (front controller in MVC pattern) used for dispatching
* to the controllers depend on the current action.
*
* @author Christian Fasanando <christian1827@gmail.com> - Beeznest
*/
// Delete the globals['_cid'], we don't need it here.
$cidReset = true; // Flag forcing the 'current course' reset
$cidReset = true;
require_once __DIR__.'/../inc/global.inc.php';
$ctok = Security::get_existing_token();
// Get Limit data
$limit = CoursesController::getLimitArray();
$limit = CoursesAndSessionsCatalog::getLimitArray();
// Section for the tabs.
$this_section = SECTION_CATALOG;
@ -29,35 +23,18 @@ if (api_get_setting('course_catalog_published') !== 'true') {
}
// For students
$user_can_view_page = true;
$userCanViewPage = true;
if (api_get_setting('allow_students_to_browse_courses') === 'false') {
$user_can_view_page = false;
$userCanViewPage = false;
}
//For teachers/admins
if (api_is_platform_admin() || api_is_course_admin() || api_is_allowed_to_create_course()) {
$user_can_view_page = true;
}
// filter actions
$actions = [
'subscribe',
'display_courses',
'display_random_courses',
'subscribe_user_with_password',
'display_sessions',
'subscribe_to_session',
'search_tag',
'search_session_title',
'subscribe_course_validation',
'subscribe_course',
];
$action = CoursesAndSessionsCatalog::is(CATALOG_SESSIONS) ? 'display_sessions' : 'display_courses';
if (isset($_GET['action']) && in_array($_GET['action'], $actions)) {
$action = Security::remove_XSS($_GET['action']);
$userCanViewPage = true;
}
$defaultAction = CoursesAndSessionsCatalog::is(CATALOG_SESSIONS) ? 'display_sessions' : 'display_courses';
$action = isset($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : $defaultAction;
$categoryCode = isset($_GET['category_code']) && !empty($_GET['category_code']) ? $_GET['category_code'] : 'ALL';
$searchTerm = isset($_REQUEST['search_term']) ? Security::remove_XSS($_REQUEST['search_term']) : '';
@ -77,49 +54,33 @@ if (empty($nameTools)) {
$interbreadcrumb[] = ['url' => '#', 'name' => $nameTools];
}
// course description controller object
$courseController = new CoursesController();
// search courses
if (isset($_REQUEST['search_course'])) {
if (!empty($_REQUEST['sec_token']) && $ctok == $_REQUEST['sec_token']) {
$courseController->search_courses(
$searchTerm,
null,
null,
null,
$limit,
true
);
exit;
}
}
// We are unsubscribing from a course (=Unsubscribe from course).
if (isset($_GET['unsubscribe'])) {
if (!empty($_GET['sec_token']) && $ctok == $_GET['sec_token']) {
$courseController->unsubscribe_user_from_course(
$_GET['unsubscribe'],
$searchTerm,
$categoryCode
);
}
}
// We are unsubscribing from a course (=Unsubscribe from course).
if (isset($_POST['unsubscribe'])) {
if (!empty($_POST['sec_token']) && $ctok == $_POST['sec_token']) {
$courseController->unsubscribe_user_from_course($_POST['unsubscribe']);
}
}
$auth = new Auth();
$userId = api_get_user_id();
$currentUrl = api_get_path(WEB_CODE_PATH).'auth/courses.php?category_code='.$categoryCode.'&search_term='.$searchTerm;
$content = '';
$toolTitle = get_lang('CourseCatalog');
switch ($action) {
case 'unsubscribe':
// We are unsubscribing from a course (=Unsubscribe from course).
if (!empty($_GET['sec_token']) && $ctok == $_GET['sec_token']) {
$result = $auth->remove_user_from_course($_GET['course_code']);
if ($result) {
Display::addFlash(
Display::return_message(get_lang('YouAreNowUnsubscribed'))
);
}
}
header('Location: '.$currentUrl);
exit;
break;
case 'subscribe_course':
if (api_is_anonymous()) {
header('Location: '.api_get_path(WEB_CODE_PATH).'auth/inscription.php?c='.$courseCodeToSubscribe);
exit;
}
$courseCodeToSubscribe = isset($_GET['subscribe_course']) ? Security::remove_XSS($_GET['subscribe_course']) : '';
$courseCodeToSubscribe = isset($_GET['course_code']) ? Security::remove_XSS($_GET['course_code']) : '';
if (Security::check_token('get')) {
CourseManager::autoSubscribeToCourse($courseCodeToSubscribe);
header('Location: '.api_get_self());
@ -127,7 +88,8 @@ switch ($action) {
}
break;
case 'subscribe_course_validation':
$courseCodeToSubscribe = isset($_GET['subscribe_course']) ? Security::remove_XSS($_GET['subscribe_course']) : '';
$toolTitle = get_lang('Subscribe');
$courseCodeToSubscribe = isset($_GET['course_code']) ? Security::remove_XSS($_GET['course_code']) : '';
$courseInfo = api_get_course_info($courseCodeToSubscribe);
if (empty($courseInfo)) {
header('Location: '.api_get_self());
@ -137,7 +99,7 @@ switch ($action) {
$message .= $courseInfo['title'].' ('.$courseInfo['visual_code'].') ';
$action = api_get_self().'?action=subscribe_course_validation&sec_token='.
Security::getTokenFromSession().'&subscribe_course='.$courseCodeToSubscribe;
Security::getTokenFromSession().'&course_code='.$courseInfo['code'];
$form = new FormValidator(
'subscribe_user_with_password',
'post',
@ -162,47 +124,310 @@ switch ($action) {
}
}
$template = new Template(get_lang('Subscribe'), true, true, false, false, false);
$template->assign('content', $content);
$template->display_one_col_template();
break;
case 'subscribe':
if (!$user_can_view_page) {
if (!$userCanViewPage) {
api_not_allowed(true);
}
header('Location: '.api_get_self());
exit;
break;
case 'display_random_courses':
if (!$user_can_view_page) {
case 'display_courses':
case 'search_course':
if (!$userCanViewPage) {
api_not_allowed(true);
}
$listCategories = CoursesAndSessionsCatalog::getCourseCategoriesTree();
$countCoursesInCategory = CourseCategory::countCoursesInCategory($categoryCode, $searchTerm);
if ($action === 'display_random_courses') {
// Random value is used instead limit filter
$browse_courses_in_category = CoursesAndSessionsCatalog::getCoursesInCategory(null, 12);
$countCoursesInCategory = count($data['browse_courses_in_category']);
} elseif($action === 'search_course' && $categoryCode !== 'ALL') {
$browse_courses_in_category = CoursesAndSessionsCatalog::search_courses(
$searchTerm,
$limit
);
$countCoursesInCategory = CourseCategory::countCoursesInCategory('ALL', $searchTerm);
} else {
if (!isset($categoryCode)) {
$categoryCode = $listCategories['ALL']['code']; // by default first category
}
$browse_courses_in_category = CoursesAndSessionsCatalog::getCoursesInCategory($categoryCode, null, $limit);
}
$courseController->courses_categories($action);
break;
case 'display_courses':
if (!$user_can_view_page) {
api_not_allowed(true);
$list_categories = $listCategories;
$code = Security::remove_XSS($categoryCode);
// getting all the courses to which the user is subscribed to
$user_courses = $auth->get_courses_of_user($userId);
$user_coursecodes = [];
// we need only the course codes as these will be used to match against the courses of the category
if ($user_courses != '') {
foreach ($user_courses as $key => $value) {
$user_coursecodes[] = $value['code'];
}
}
$courseController->courses_categories(
$action,
$categoryCode,
null,
null,
null,
$limit
);
if (api_is_drh()) {
$courses = CourseManager::get_courses_followed_by_drh($userId);
foreach ($courses as $course) {
$user_coursecodes[] = $course['code'];
}
}
$catalogShowCoursesSessions = 0;
$showCoursesSessions = (int) api_get_setting('catalog_show_courses_sessions');
if ($showCoursesSessions > 0) {
$catalogShowCoursesSessions = $showCoursesSessions;
}
$showCourses = CoursesAndSessionsCatalog::showCourses();
$showSessions = CoursesAndSessionsCatalog::showSessions();
$pageCurrent = isset($_GET['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
$pageLength = isset($_GET['pageLength']) ? (int) $_GET['pageLength'] : CoursesAndSessionsCatalog::PAGE_LENGTH;
$pageTotal = (int) ceil($countCoursesInCategory / $pageLength);
$catalogPagination = '';
if ($pageTotal > 1) {
$catalogPagination = CourseCategory::getCatalogPagination(
$pageCurrent,
$pageLength,
$pageTotal,
$categoryCode,
$action
);
}
$date = date('Y-m-d');
if ($showSessions && isset($_POST['date'])) {
$date = $_POST['date'];
}
$userInfo = api_get_user_info();
$code = isset($code) ? $code : null;
$extraDate = '';
if ($showSessions) {
$extraDate = "
$('#date').datepicker({
dateFormat: 'yy-mm-dd'
});";
}
$htmlHeadXtra[] = "
<script>
$(function() {
$('.star-rating li a').on('click', function(event) {
var id = $(this).parents('ul').attr('id');
$('#vote_label2_' + id).html('".get_lang('Loading')."');
$.ajax({
url: $(this).attr('data-link'),
success: function(data) {
$('#rating_wrapper_'+id).html(data);
}
});
});
var getSessionId = function (el) {
var parts = el.id.split('_');
return parseInt(parts[1], 10);
};
$extraDate
});
</script>";
$stok = Security::get_token();
$content = CoursesAndSessionsCatalog::getTabList(1);
$content .= '<div class="row">
<div class="col-md-12">
<div class="search-courses">
<div class="row">';
if ($showCourses) {
$content .= '<div class="col-md-'.($showSessions ? '4' : '6').'">';
if (!isset($_GET['hidden_links']) || intval($_GET['hidden_links']) != 1) {
$content .= '
<form method="post"
action="'.CourseCategory::getCourseCategoryUrl(1, $pageLength, 'ALL', 0, 'search_course').'">
<input type="hidden" name="sec_token" value="'.$stok.'">
<label>'.get_lang('Search').'</label>
<div class="input-group">
<input class="form-control" type="text" name="search_term"
value="'.(empty($_POST['search_term']) ? '' : api_htmlentities($searchTerm)).'"/>
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<em class="fa fa-search"></em>'.get_lang('Search').'
</button>
</div>
</div>
</form>';
}
$content .= '</div>';
$content .= '<div class="col-md-'.($showSessions ? '4' : '6').'">';
$listCategories = CoursesAndSessionsCatalog::getCourseCategoriesTree();
$categoriesSelect = CoursesAndSessionsCatalog::getOptionSelect($listCategories, $categoryCode);
$webAction = api_get_path(WEB_CODE_PATH).'auth/courses.php';
$form = '<form action="'.$webAction.'" method="GET">';
$form .= '<input type="hidden" name="action" value="'.$action.'">';
$form .= '<input type="hidden" name="pageCurrent" value="'.$pageCurrent.'">';
$form .= '<input type="hidden" name="pageLength" value="'.$pageLength.'">';
$form .= '<div class="form-group">';
$form .= '<label>'.get_lang('CourseCategories').'</label>';
$form .= $categoriesSelect;
$form .= '</div>';
$form .= '</form>';
$content .= $form;
$content .= '</div>';
}
$content .= '</div></div></div></div>';
if ($showCourses) {
if (!empty($searchTerm)) {
$content .= "<p><strong>".get_lang('SearchResultsFor')." ".$searchTerm."</strong><br />";
}
$showTeacher = api_get_setting('display_teacher_in_courselist') === 'true';
$ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
$user_id = api_get_user_id();
$categoryListFromDatabase = CourseCategory::getAllCategories();
$categoryList = [];
if (!empty($categoryListFromDatabase)) {
foreach ($categoryListFromDatabase as $categoryItem) {
$categoryList[$categoryItem['code']] = $categoryItem['name'];
}
}
if (!empty($browse_courses_in_category)) {
$content .= '<div class="grid-courses row">';
foreach ($browse_courses_in_category as $course) {
$course_hidden = $course['visibility'] == COURSE_VISIBILITY_HIDDEN;
if ($course_hidden) {
continue;
}
$userRegisteredInCourse = CourseManager::is_user_subscribed_in_course($user_id, $course['code']);
$userRegisteredInCourseAsTeacher = CourseManager::is_course_teacher($user_id, $course['code']);
$userRegistered = $userRegisteredInCourse && $userRegisteredInCourseAsTeacher;
$course_public = $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD;
$course_open = $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM;
$course_private = $course['visibility'] == COURSE_VISIBILITY_REGISTERED;
$course_closed = $course['visibility'] == COURSE_VISIBILITY_CLOSED;
$course_subscribe_allowed = $course['subscribe'] == 1;
$course_unsubscribe_allowed = $course['unsubscribe'] == 1;
$count_connections = $course['count_connections'];
$creation_date = substr($course['creation_date'], 0, 10);
// display the course bloc
$html = '<div class="col-xs-12 col-sm-6 col-md-4"><div class="items items-courses">';
$course['category_title'] = '';
if (isset($course['category'])) {
$course['category_title'] = isset($categoryList[$course['category']]) ? $categoryList[$course['category']] : '';
}
// Display thumbnail
$html .= CoursesAndSessionsCatalog::returnThumbnail($course, $userRegistered);
$separator = null;
$subscribeButton = CoursesAndSessionsCatalog::return_register_button($course, $stok, $code, $searchTerm);
// Start buy course validation
// display the course price and buy button if the buycourses plugin is enabled and this course is configured
$plugin = BuyCoursesPlugin::create();
$isThisCourseInSale = $plugin->buyCoursesForGridCatalogValidator(
$course['real_id'],
BuyCoursesPlugin::PRODUCT_TYPE_COURSE
);
if ($isThisCourseInSale) {
// set the Price label
$separator = $isThisCourseInSale['html'];
// set the Buy button instead register.
if ($isThisCourseInSale['verificator']) {
$subscribeButton = $plugin->returnBuyCourseButton(
$course['real_id'],
BuyCoursesPlugin::PRODUCT_TYPE_COURSE
);
}
}
// end buy course validation
// display course title and button bloc
$html .= '<div class="description">';
$html .= CoursesAndSessionsCatalog::return_title($course, $userRegisteredInCourse);
if ($showTeacher) {
$html .= CoursesAndSessionsCatalog::return_teacher($course);
}
// display button line
$html .= '<div class="toolbar row">';
$html .= $separator ? '<div class="col-sm-4">'.$separator.'</div>' : '';
$html .= '<div class="col-sm-8">';
// if user registered as student
if ($userRegisteredInCourse) {
$html .= CoursesAndSessionsCatalog::return_already_registered_label('student');
if (!$course_closed) {
if ($course_unsubscribe_allowed) {
$html .= CoursesAndSessionsCatalog::return_unregister_button($course, $stok, $searchTerm, $code);
}
}
} elseif ($userRegisteredInCourseAsTeacher) {
// if user registered as teacher
if ($course_unsubscribe_allowed) {
$html .= CoursesAndSessionsCatalog::return_unregister_button($course, $stok, $searchTerm, $code);
}
} else {
// if user not registered in the course
if (!$course_closed) {
if (!$course_private) {
if ($course_subscribe_allowed) {
$html .= $subscribeButton;
}
}
}
}
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
$content .= $html;
}
$content .= '</div>';
} else {
if (!isset($_REQUEST['subscribe_user_with_password']) &&
!isset($_REQUEST['subscribe_course'])
) {
$content .= Display::return_message(
get_lang('ThereAreNoCoursesInThisCategory'),
'warning'
);
}
}
}
$content .= '<div class="col-md-12">';
$content .= $catalogPagination;
$content .= '</div>';
break;
case 'display_sessions':
if (!$user_can_view_page) {
if (!$userCanViewPage) {
api_not_allowed(true);
}
$courseController->sessionList($limit);
CoursesAndSessionsCatalog::sessionList($limit);
exit;
break;
case 'subscribe_to_session':
if (!$user_can_view_page) {
if (!$userCanViewPage) {
api_not_allowed(true);
}
@ -275,17 +500,23 @@ switch ($action) {
}
break;
case 'search_tag':
if (!$user_can_view_page) {
if (!$userCanViewPage) {
api_not_allowed(true);
}
$courseController->sessionsListByCoursesTag($limit);
CoursesAndSessionsCatalog::sessionsListByCoursesTag($limit);
exit;
break;
case 'search_session_title':
if (!$user_can_view_page) {
if (!$userCanViewPage) {
api_not_allowed(true);
}
$courseController->sessionsListByName($limit);
CoursesAndSessionsCatalog::sessionsListByName($limit);
break;
}
$template = new Template($toolTitle, true, true, false, false, false);
$template->assign('content', $content);
$template->display_one_col_template();

@ -1,523 +0,0 @@
<?php
/* For licensing terms, see /license.txt */
/**
* View (MVC patter) for courses categories.
*
* @author Christian Fasanando <christian1827@gmail.com> - Beeznest
*/
if (isset($_REQUEST['action']) && Security::remove_XSS($_REQUEST['action']) !== 'subscribe') {
$stok = Security::get_token();
} else {
$stok = Security::getTokenFromSession();
}
$action = !empty($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : 'display_courses';
global $actions;
$action = in_array($action, $actions) ? $action : 'display_courses';
$showCourses = CoursesAndSessionsCatalog::showCourses();
$showSessions = CoursesAndSessionsCatalog::showSessions();
$pageCurrent = isset($_GET['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
$pageLength = isset($_GET['pageLength']) ? (int) $_GET['pageLength'] : CoursesAndSessionsCatalog::PAGE_LENGTH;
$pageTotal = (int) ceil((int) $countCoursesInCategory / $pageLength);
$cataloguePagination = $pageTotal > 1 ? CourseCategory::getCatalogPagination($pageCurrent, $pageLength, $pageTotal) : '';
$searchTerm = isset($_REQUEST['search_term']) ? Security::remove_XSS($_REQUEST['search_term']) : '';
$codeType = isset($_REQUEST['category_code']) ? Security::remove_XSS($_REQUEST['category_code']) : '';
$date = date('Y-m-d');
if ($showSessions && isset($_POST['date'])) {
$date = $_POST['date'];
}
$userInfo = api_get_user_info();
$code = isset($code) ? $code : null;
?>
<script>
$(function() {
$('.star-rating li a').on('click', function(event) {
var id = $(this).parents('ul').attr('id');
$('#vote_label2_' + id).html("<?php echo get_lang('Loading'); ?>");
$.ajax({
url: $(this).attr('data-link'),
success: function(data) {
$("#rating_wrapper_"+id).html(data);
}
});
});
var getSessionId = function (el) {
var parts = el.id.split('_');
return parseInt(parts[1], 10);
};
<?php if ($showSessions) {
?>
$('#date').datepicker({
dateFormat: 'yy-mm-dd'
});
<?php
} ?>
});
</script>
<?php
echo CoursesController::getTabList(1);
echo '<div class="row">
<div class="col-md-12">
<div class="search-courses">
<div class="row">';
if ($showCourses) {
echo '<div class="col-md-'.($showSessions ? '4' : '6').'">';
if (!isset($_GET['hidden_links']) || intval($_GET['hidden_links']) != 1) {
?>
<form method="post"
action="<?php echo CourseCategory::getCourseCategoryUrl(1, $pageLength, 'ALL', 0, 'subscribe'); ?>">
<input type="hidden" name="sec_token" value="<?php echo $stok; ?>">
<input type="hidden" name="search_course" value="1"/>
<label><?php echo get_lang('Search'); ?></label>
<div class="input-group">
<input class="form-control" type="text" name="search_term"
value="<?php echo empty($_POST['search_term']) ? '' : api_htmlentities($searchTerm); ?>"/>
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<em class="fa fa-search"></em> <?php echo get_lang('Search'); ?>
</button>
</div>
</div>
</form>
<?php
}
echo '</div>';
echo '<div class="col-md-'.($showSessions ? '4' : '6').'">';
$listCategories = CoursesAndSessionsCatalog::getCourseCategoriesTree();
$categoriesSelect = getOptionSelect($listCategories, $codeType);
$webAction = api_get_path(WEB_CODE_PATH).'auth/courses.php';
$form = '<form action="'.$webAction.'" method="GET">';
$form .= '<input type="hidden" name="action" value="'.$action.'">';
$form .= '<input type="hidden" name="pageCurrent" value="'.$pageCurrent.'">';
$form .= '<input type="hidden" name="pageLength" value="'.$pageLength.'">';
$form .= '<div class="form-group">';
$form .= '<label>'.get_lang('CourseCategories').'</label>';
$form .= $categoriesSelect;
$form .= '</div>';
$form .= '</form>';
echo $form;
echo '</div>';
}
echo '</div></div></div></div>';
if ($showCourses && $action != 'display_sessions') {
if (!empty($message)) {
echo Display::return_message($message, 'confirmation', false);
}
if (!empty($error)) {
echo Display::return_message($error, 'error', false);
}
if (!empty($content)) {
echo $content;
}
if (!empty($searchTerm)) {
echo "<p><strong>".get_lang('SearchResultsFor')." ".$searchTerm."</strong><br />";
}
$showTeacher = api_get_setting('display_teacher_in_courselist') === 'true';
$ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
$user_id = api_get_user_id();
$categoryListFromDatabase = CourseCategory::getAllCategories();
$categoryList = [];
if (!empty($categoryListFromDatabase)) {
foreach ($categoryListFromDatabase as $categoryItem) {
$categoryList[$categoryItem['code']] = $categoryItem['name'];
}
}
if (!empty($browse_courses_in_category)) {
echo '<div class="grid-courses row">';
foreach ($browse_courses_in_category as $course) {
$course_hidden = $course['visibility'] == COURSE_VISIBILITY_HIDDEN;
if ($course_hidden) {
continue;
}
$userRegisteredInCourse = CourseManager::is_user_subscribed_in_course($user_id, $course['code']);
$userRegisteredInCourseAsTeacher = CourseManager::is_course_teacher($user_id, $course['code']);
$userRegistered = $userRegisteredInCourse && $userRegisteredInCourseAsTeacher;
$course_public = $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD;
$course_open = $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM;
$course_private = $course['visibility'] == COURSE_VISIBILITY_REGISTERED;
$course_closed = $course['visibility'] == COURSE_VISIBILITY_CLOSED;
$course_subscribe_allowed = $course['subscribe'] == 1;
$course_unsubscribe_allowed = $course['unsubscribe'] == 1;
$count_connections = $course['count_connections'];
$creation_date = substr($course['creation_date'], 0, 10);
// display the course bloc
$html = '<div class="col-xs-12 col-sm-6 col-md-4"><div class="items items-courses">';
$course['category_title'] = '';
if (isset($course['category'])) {
$course['category_title'] = isset($categoryList[$course['category']]) ? $categoryList[$course['category']] : '';
}
// Display thumbnail
$html .= returnThumbnail($course, $userRegistered);
$separator = null;
$subscribeButton = return_register_button($course, $stok, $code, $searchTerm);
// Start buy course validation
// display the course price and buy button if the buycourses plugin is enabled and this course is configured
$plugin = BuyCoursesPlugin::create();
$isThisCourseInSale = $plugin->buyCoursesForGridCatalogValidator(
$course['real_id'],
BuyCoursesPlugin::PRODUCT_TYPE_COURSE
);
if ($isThisCourseInSale) {
// set the Price label
$separator = $isThisCourseInSale['html'];
// set the Buy button instead register.
if ($isThisCourseInSale['verificator']) {
$subscribeButton = $plugin->returnBuyCourseButton(
$course['real_id'],
BuyCoursesPlugin::PRODUCT_TYPE_COURSE
);
}
}
// end buy course validation
// display course title and button bloc
$html .= '<div class="description">';
$html .= return_title($course, $userRegisteredInCourse);
if ($showTeacher) {
$html .= return_teacher($course);
}
// display button line
$html .= '<div class="toolbar row">';
$html .= $separator ? '<div class="col-sm-4">'.$separator.'</div>' : '';
$html .= '<div class="col-sm-8">';
// if user registered as student
if ($userRegisteredInCourse) {
$html .= return_already_registered_label('student');
if (!$course_closed) {
if ($course_unsubscribe_allowed) {
$html .= return_unregister_button($course, $stok, $searchTerm, $code);
}
}
} elseif ($userRegisteredInCourseAsTeacher) {
// if user registered as teacher
if ($course_unsubscribe_allowed) {
$html .= return_unregister_button($course, $stok, $searchTerm, $code);
}
} else {
// if user not registered in the course
if (!$course_closed) {
if (!$course_private) {
if ($course_subscribe_allowed) {
$html .= $subscribeButton;
}
}
}
}
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
echo $html;
}
echo '</div>';
} else {
if (!isset($_REQUEST['subscribe_user_with_password']) &&
!isset($_REQUEST['subscribe_course'])
) {
echo Display::return_message(
get_lang('ThereAreNoCoursesInThisCategory'),
'warning'
);
}
}
}
echo '<div class="col-md-12">';
echo $cataloguePagination;
echo '</div>';
function getOptionSelect($categories, $codeType)
{
$html = '';
$html .= '<select name="category_code" onchange="submit();" class="selectpicker form-control">';
foreach ($categories as $category) {
$categoryCode = Security::remove_XSS($category['code']);
$categoryName = Security::remove_XSS($category['name']);
$countCourse = (int) $category['number_courses'];
$level = $category['level'];
if (empty($countCourse)) {
continue;
}
if ($level > 0) {
$separate = str_repeat('--', $level);
} else {
$separate = '';
}
$html .= '<option '.($categoryCode == $codeType ? 'selected="selected" ' : '')
.' value="'.$categoryCode.'">'.$separate.' '.$categoryName.' ('.$countCourse.') </option>';
}
$html .= '</select>';
return $html;
}
/**
* Display the course catalog image of a course.
*
* @param array $course
* @param bool $registeredUser
*
* @return string HTML string
*/
function returnThumbnail($course, $registeredUser)
{
$html = '';
$title = cut($course['title'], 70);
//$linkCourse = api_get_course_url($course['code']);
$linkCourse = api_get_path(WEB_PATH).'course/'.$course['real_id'].'/about';
// course path
$course_path = api_get_path(SYS_COURSE_PATH).$course['directory'];
if (file_exists($course_path.'/course-pic.png')) {
// redimensioned image 85x85
$courseMediumImage = api_get_path(WEB_COURSE_PATH).$course['directory'].'/course-pic.png';
} else {
// without picture
$courseMediumImage = Display::return_icon(
'session_default.png',
null,
null,
null,
null,
true
);
}
$html .= '<div class="image">';
$html .= '<a href="'.$linkCourse.'" title="'.$course['title'].'">'
.'<img class="img-responsive" src="'.$courseMediumImage.'" '
.'alt="'.api_htmlentities($title).'"/></a>';
$categoryTitle = isset($course['category_title']) ? $course['category_title'] : '';
if (!empty($categoryTitle)) {
$html .= '<span class="category">'.$categoryTitle.'</span>';
$html .= '<div class="cribbon"></div>';
}
$html .= '<div class="user-actions">';
$html .= CourseManager::returnDescriptionButton($course);
$html .= '</div></div>';
return $html;
}
/**
* @param array $courseInfo
*
* @return string
*/
function return_teacher($courseInfo)
{
$teachers = CourseManager::getTeachersFromCourse($courseInfo['real_id']);
$length = count($teachers);
if (!$length) {
return '';
}
$html = '<div class="block-author">';
if ($length > 6) {
$html .= '<a
id="plist"
data-trigger="focus"
tabindex="0" role="button"
class="btn btn-default panel_popover"
data-toggle="popover"
title="'.addslashes(get_lang('CourseTeachers')).'"
data-html="true"
>
<i class="fa fa-graduation-cap" aria-hidden="true"></i>
</a>';
$html .= '<div id="popover-content-plist" class="hide">';
foreach ($teachers as $value) {
$name = $value['firstname'].' '.$value['lastname'];
$html .= '<div class="popover-teacher">';
$html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
<img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
$html .= '<div class="teachers-details"><h5>
<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">'
.$name.'</a></h5></div>';
$html .= '</div>';
}
$html .= '</div>';
} else {
foreach ($teachers as $value) {
$name = $value['firstname'].' '.$value['lastname'];
if ($length > 2) {
$html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
<img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
} else {
$html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
<img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
$html .= '<div class="teachers-details"><h5>
<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'">'
.$name.'</a></h5><p>'.get_lang('Teacher').'</p></div>';
}
}
}
$html .= '</div>';
return $html;
}
/**
* Display the title of a course in course catalog.
*
* @param array $course
* @param bool $registeredUser
*
* @return string HTML string
*/
function return_title($course, $registeredUser)
{
//$linkCourse = api_get_course_url($course['code']);
$linkCourse = api_get_path(WEB_PATH).'course/'.$course['real_id'].'/about';
$html = '<div class="block-title"><h4 class="title">';
$html .= '<a title="'.$course['title'].'" href="'.$linkCourse.'">'.$course['title'].'</a>';
$html .= '</h4></div>';
if (api_get_configuration_value('hide_course_rating') === false) {
$ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
$rating = Display::return_rating_system(
'star_'.$course['real_id'],
$ajax_url.'&course_id='.$course['real_id'],
$course['point_info']
);
$html .= '<div class="ranking">'.$rating.'</div>';
}
return $html;
}
/**
* Display the goto course button of a course in the course catalog.
*
* @param $course
*
* @return string HTML string
*/
function return_goto_button($course)
{
$title = get_lang('GoToCourse');
$html = Display::url(
Display::returnFontAwesomeIcon('share'),
api_get_course_url($course['code']),
[
'class' => 'btn btn-default btn-sm',
'title' => $title,
'aria-label' => $title,
]
);
return $html.PHP_EOL;
}
/**
* Display the already registerd text in a course in the course catalog.
*
* @param $in_status
*
* @return string HTML string
*/
function return_already_registered_label($in_status)
{
$icon = '<em class="fa fa-check"></em>';
$title = get_lang("YouAreATeacherOfThisCourse");
if ($in_status == 'student') {
$icon = '<em class="fa fa-check"></em>';
$title = get_lang("AlreadySubscribed");
}
$html = Display::tag(
'span',
$icon.' '.$title,
[
'id' => 'register',
'class' => 'label-subscribed text-success',
'title' => $title,
'aria-label' => $title,
]
);
return $html.PHP_EOL;
}
/**
* Display the register button of a course in the course catalog.
*
* @param $course
* @param $stok
* @param $code
* @param $search_term
*
* @return string
*/
function return_register_button($course, $stok, $code, $search_term)
{
$title = get_lang('Subscribe');
$action = 'subscribe_course';
if (!empty($course['registration_code'])) {
$action = 'subscribe_course_validation';
}
$html = Display::url(
Display::returnFontAwesomeIcon('check').' '.$title,
api_get_self().'?action='.$action.'&sec_token='.$stok.
'&subscribe_course='.$course['code'].'&search_term='.$search_term.'&category_code='.$code,
['class' => 'btn btn-success btn-sm', 'title' => $title, 'aria-label' => $title]
);
return $html;
}
/**
* Display the unregister button of a course in the course catalog.
*
* @param $course
* @param $stok
* @param $search_term
* @param $code
*
* @return string
*/
function return_unregister_button($course, $stok, $search_term, $code)
{
$title = get_lang('Unsubscription');
$html = Display::url(
Display::returnFontAwesomeIcon('sign-in').' '.$title,
api_get_self().'?action=unsubscribe&sec_token='.$stok
.'&unsubscribe='.$course['code'].'&search_term='.$search_term.'&category_code='.$code,
['class' => 'btn btn-danger btn-sm', 'title' => $title, 'aria-label' => $title]
);
return $html;
}

@ -1,684 +0,0 @@
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\Repository\SequenceResourceRepository;
use Chamilo\CoreBundle\Entity\SequenceResource;
use Chamilo\CoreBundle\Entity\SessionRelCourse;
use Chamilo\CoreBundle\Entity\Tag;
/**
* Class CoursesController.
*
* This file contains class used like controller,
* it should be included inside a dispatcher file (e.g: index.php)
*
* @author Christian Fasanando <christian1827@gmail.com> - BeezNest
*
* @package chamilo.auth
*/
class CoursesController
{
private $toolname;
private $view;
private $model;
/**
* Constructor.
*/
public function __construct()
{
$this->toolname = 'auth';
//$actived_theme_path = api_get_template();
$this->view = new View($this->toolname);
$this->model = new Auth();
}
/**
* It's used for listing courses with categories,
* render to courses_categories view.
*
* @param string $action
* @param string $category_code
* @param string $message
* @param string $error
* @param string $content
* @param array $limit will be used if $random_value is not set.
* This array should contains 'start' and 'length' keys
*
* @internal param \action $string
* @internal param \Category $string code (optional)
*/
public function courses_categories(
$action,
$category_code = null,
$message = '',
$error = '',
$content = null,
$limit = []
) {
$data = [];
$listCategories = CoursesAndSessionsCatalog::getCourseCategoriesTree();
$data['countCoursesInCategory'] = CourseCategory::countCoursesInCategory($category_code);
if ($action === 'display_random_courses') {
// Random value is used instead limit filter
$data['browse_courses_in_category'] = CoursesAndSessionsCatalog::getCoursesInCategory(null, 12);
$data['countCoursesInCategory'] = count($data['browse_courses_in_category']);
} else {
if (!isset($category_code)) {
$category_code = $listCategories['ALL']['code']; // by default first category
}
$limit = isset($limit) ? $limit : self::getLimitArray();
$listCourses = CoursesAndSessionsCatalog::getCoursesInCategory($category_code, null, $limit);
$data['browse_courses_in_category'] = $listCourses;
}
$data['list_categories'] = $listCategories;
$data['code'] = Security::remove_XSS($category_code);
// getting all the courses to which the user is subscribed to
$curr_user_id = api_get_user_id();
$user_courses = $this->model->get_courses_of_user($curr_user_id);
$user_coursecodes = [];
// we need only the course codes as these will be used to match against the courses of the category
if ($user_courses != '') {
foreach ($user_courses as $key => $value) {
$user_coursecodes[] = $value['code'];
}
}
if (api_is_drh()) {
$courses = CourseManager::get_courses_followed_by_drh(api_get_user_id());
foreach ($courses as $course) {
$user_coursecodes[] = $course['code'];
}
}
$data['user_coursecodes'] = $user_coursecodes;
$data['action'] = $action;
$data['message'] = $message;
$data['content'] = $content;
$data['error'] = $error;
$data['catalogShowCoursesSessions'] = 0;
$showCoursesSessions = (int) api_get_setting('catalog_show_courses_sessions');
if ($showCoursesSessions > 0) {
$data['catalogShowCoursesSessions'] = $showCoursesSessions;
}
// render to the view
$this->view->set_data($data);
$this->view->set_layout('layout');
$this->view->set_template('courses_categories');
$this->view->render();
}
/**
* @param string $search_term
* @param string $message
* @param string $error
* @param string $content
* @param array $limit
* @param bool $justVisible Whether to search only in courses visibles in the catalogue
*/
public function search_courses(
$search_term,
$message = '',
$error = '',
$content = null,
$limit = [],
$justVisible = false
) {
$data = [];
$limit = !empty($limit) ? $limit : self::getLimitArray();
$browse_course_categories = CoursesAndSessionsCatalog::getCourseCategories();
$data['countCoursesInCategory'] = CourseCategory::countCoursesInCategory('ALL', $search_term);
$data['browse_courses_in_category'] = CoursesAndSessionsCatalog::search_courses(
$search_term,
$limit,
$justVisible
);
$data['browse_course_categories'] = $browse_course_categories;
$data['search_term'] = Security::remove_XSS($search_term); //filter before showing in template
// getting all the courses to which the user is subscribed to
$curr_user_id = api_get_user_id();
$user_courses = $this->model->get_courses_of_user($curr_user_id);
$user_coursecodes = [];
// we need only the course codes as these will be used to match against the courses of the category
if ($user_courses != '') {
foreach ($user_courses as $value) {
$user_coursecodes[] = $value['code'];
}
}
$data['user_coursecodes'] = $user_coursecodes;
$data['message'] = $message;
$data['content'] = $content;
$data['error'] = $error;
$data['action'] = 'display_courses';
// render to the view
$this->view->set_data($data);
$this->view->set_layout('catalog_layout');
$this->view->set_template('courses_categories');
$this->view->render();
}
/**
* Unsubscribe user from a course
* render to listing view.
*
* @param string $course_code
* @param string $search_term
* @param string $category_code
*/
public function unsubscribe_user_from_course(
$course_code,
$search_term = null,
$category_code = null
) {
$result = $this->model->remove_user_from_course($course_code);
$message = '';
$error = '';
if ($result) {
Display::addFlash(
Display::return_message(get_lang('YouAreNowUnsubscribed'))
);
}
if (!empty($search_term)) {
CoursesAndSessionsCatalog::search_courses($search_term, $message, $error);
} else {
$this->courses_categories(
'subcribe',
$category_code,
$message,
$error
);
}
}
/**
* Get a HTML button for subscribe to session.
*
* @param int $sessionId The session ID
* @param string $sessionName The session name
* @param bool $checkRequirements Optional.
* Whether the session has requirement. Default is false
* @param bool $includeText Optional. Whether show the text in button
* @param bool $btnBing
*
* @return string The button HTML
*/
public function getRegisteredInSessionButton(
$sessionId,
$sessionName,
$checkRequirements = false,
$includeText = false,
$btnBing = false
) {
$sessionId = (int) $sessionId;
if ($btnBing) {
$btnBing = 'btn-lg btn-block';
} else {
$btnBing = 'btn-sm';
}
if ($checkRequirements) {
return $this->getRequirements($sessionId, SequenceResource::SESSION_TYPE, $includeText, $btnBing);
}
$catalogSessionAutoSubscriptionAllowed = false;
if (api_get_setting('catalog_allow_session_auto_subscription') === 'true') {
$catalogSessionAutoSubscriptionAllowed = true;
}
$url = api_get_path(WEB_CODE_PATH);
if ($catalogSessionAutoSubscriptionAllowed) {
$url .= 'auth/courses.php?';
$url .= http_build_query([
'action' => 'subscribe_to_session',
'session_id' => $sessionId,
]);
$result = Display::toolbarButton(
get_lang('Subscribe'),
$url,
'pencil',
'primary',
[
'class' => $btnBing.' ajax',
'data-title' => get_lang('AreYouSureToSubscribe'),
'data-size' => 'md',
'title' => get_lang('Subscribe'),
],
$includeText
);
} else {
$url .= 'inc/email_editor.php?';
$url .= http_build_query([
'action' => 'subscribe_me_to_session',
'session' => Security::remove_XSS($sessionName),
]);
$result = Display::toolbarButton(
get_lang('SubscribeToSessionRequest'),
$url,
'pencil',
'primary',
['class' => $btnBing],
$includeText
);
}
$hook = HookResubscribe::create();
if (!empty($hook)) {
$hook->setEventData([
'session_id' => $sessionId,
]);
try {
$hook->notifyResubscribe(HOOK_EVENT_TYPE_PRE);
} catch (Exception $exception) {
$result = $exception->getMessage();
}
}
return $result;
}
public function getRequirements($id, $type, $includeText, $btnBing)
{
$id = (int) $id;
$type = (int) $type;
$url = api_get_path(WEB_AJAX_PATH);
$url .= 'sequence.ajax.php?';
$url .= http_build_query(
[
'a' => 'get_requirements',
'id' => $id,
'type' => $type,
]
);
return Display::toolbarButton(
get_lang('CheckRequirements'),
$url,
'shield',
'info',
[
'class' => $btnBing.' ajax',
'data-title' => get_lang('CheckRequirements'),
'data-size' => 'md',
'title' => get_lang('CheckRequirements'),
],
$includeText
);
}
/**
* Generate a label if the user has been registered in session.
*
* @return string The label
*/
public function getAlreadyRegisteredInSessionLabel()
{
$icon = '<em class="fa fa-graduation-cap"></em>';
return Display::div(
$icon,
[
'class' => 'btn btn-default btn-sm registered',
'title' => get_lang("AlreadyRegisteredToSession"),
]
);
}
/**
* Get a icon for a session.
*
* @param string $sessionName The session name
*
* @return string The icon
*/
public function getSessionIcon($sessionName)
{
return Display::return_icon(
'window_list.png',
$sessionName,
null,
ICON_SIZE_MEDIUM
);
}
/**
* Return Session catalog rendered view.
*
* @param array $limit
*/
public function sessionList($limit = [])
{
$date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
$hiddenLinks = isset($_GET['hidden_links']) ? $_GET['hidden_links'] == 1 : false;
$limit = isset($limit) ? $limit : self::getLimitArray();
$countSessions = CoursesAndSessionsCatalog::browseSessions($date, [], false, true);
$sessions = CoursesAndSessionsCatalog::browseSessions($date, $limit);
$pageTotal = ceil($countSessions / $limit['length']);
// Do NOT show pagination if only one page or less
$pagination = $pageTotal > 1 ? CourseCategory::getCatalogPagination($limit['current'], $limit['length'], $pageTotal) : '';
$sessionsBlocks = $this->getFormattedSessionsBlock($sessions);
// Get session search catalogue URL
$courseUrl = CourseCategory::getCourseCategoryUrl(
1,
$limit['length'],
null,
0,
'subscribe'
);
$tpl = new Template();
$tpl->assign('actions', self::getTabList(2));
$tpl->assign('show_courses', CoursesAndSessionsCatalog::showCourses());
$tpl->assign('show_sessions', CoursesAndSessionsCatalog::showSessions());
$tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true');
$tpl->assign('course_url', $courseUrl);
$tpl->assign('catalog_pagination', $pagination);
$tpl->assign('hidden_links', $hiddenLinks);
$tpl->assign('search_token', Security::get_token());
$tpl->assign('search_date', $date);
$tpl->assign('web_session_courses_ajax_url', api_get_path(WEB_AJAX_PATH).'course.ajax.php');
$tpl->assign('sessions', $sessionsBlocks);
$tpl->assign('already_subscribed_label', $this->getAlreadyRegisteredInSessionLabel());
$tpl->assign('catalog_settings', self::getCatalogSearchSettings());
$contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
$tpl->display($contentTemplate);
}
/**
* Show the Session Catalogue with filtered session by course tags.
*
* @param array $limit Limit info
*/
public function sessionsListByName(array $limit)
{
$keyword = isset($_POST['keyword']) ? $_POST['keyword'] : null;
$hiddenLinks = isset($_GET['hidden_links']) ? (int) $_GET['hidden_links'] == 1 : false;
$courseUrl = CourseCategory::getCourseCategoryUrl(
1,
$limit['length'],
null,
0,
'subscribe'
);
$sessions = CoursesAndSessionsCatalog::getSessionsByName($keyword, $limit);
$sessionsBlocks = $this->getFormattedSessionsBlock($sessions);
$tpl = new Template();
$tpl->assign('actions', self::getTabList(2));
$tpl->assign('show_courses', CoursesAndSessionsCatalog::showCourses());
$tpl->assign('show_sessions', CoursesAndSessionsCatalog::showSessions());
$tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true' ? true : false);
$tpl->assign('course_url', $courseUrl);
$tpl->assign('already_subscribed_label', $this->getAlreadyRegisteredInSessionLabel());
$tpl->assign('hidden_links', $hiddenLinks);
$tpl->assign('search_token', Security::get_token());
$tpl->assign('keyword', Security::remove_XSS($keyword));
$tpl->assign('sessions', $sessionsBlocks);
$tpl->assign('catalog_settings', self::getCatalogSearchSettings());
$contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
$tpl->display($contentTemplate);
}
public static function getCatalogSearchSettings()
{
$settings = api_get_configuration_value('catalog_settings');
if (empty($settings)) {
// Default everything is visible
$settings = [
'sessions' => [
'by_title' => true,
'by_date' => true,
'by_tag' => true,
'show_session_info' => true,
'show_session_date' => true,
],
];
}
return $settings;
}
/**
* @param int $active
*
* @return string
*/
public static function getTabList($active = 1)
{
$pageLength = isset($_GET['pageLength']) ? (int) $_GET['pageLength'] : CoursesAndSessionsCatalog::PAGE_LENGTH;
$url = CourseCategory::getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions');
$headers = [];
if (CoursesAndSessionsCatalog::showCourses()) {
$headers[] = [
'url' => api_get_self(),
'content' => get_lang('CourseManagement'),
];
}
if (CoursesAndSessionsCatalog::showSessions()) {
$headers[] = [
'url' => $url,
'content' => get_lang('SessionList'),
];
}
return Display::tabsOnlyLink($headers, $active);
}
/**
* Show the Session Catalogue with filtered session by course tags.
*
* @param array $limit Limit info
*/
public function sessionsListByCoursesTag(array $limit)
{
$searchTag = isset($_POST['search_tag']) ? $_POST['search_tag'] : null;
$searchDate = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
$hiddenLinks = isset($_GET['hidden_links']) ? (int) $_GET['hidden_links'] == 1 : false;
$courseUrl = CourseCategory::getCourseCategoryUrl(
1,
$limit['length'],
null,
0,
'subscribe'
);
$sessions = CoursesAndSessionsCatalog::browseSessionsByTags($searchTag, $limit);
$sessionsBlocks = $this->getFormattedSessionsBlock($sessions);
$tpl = new Template();
$tpl->assign('show_courses', CoursesAndSessionsCatalog::showCourses());
$tpl->assign('show_sessions', CoursesAndSessionsCatalog::showSessions());
$tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true' ? true : false);
$tpl->assign('course_url', $courseUrl);
$tpl->assign('already_subscribed_label', $this->getAlreadyRegisteredInSessionLabel());
$tpl->assign('hidden_links', $hiddenLinks);
$tpl->assign('search_token', Security::get_token());
$tpl->assign('search_date', Security::remove_XSS($searchDate));
$tpl->assign('search_tag', Security::remove_XSS($searchTag));
$tpl->assign('sessions', $sessionsBlocks);
$contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
$tpl->display($contentTemplate);
}
/**
* @return array
*/
public static function getLimitArray()
{
$pageCurrent = isset($_REQUEST['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
$pageLength = isset($_REQUEST['pageLength']) ? (int) $_GET['pageLength'] : CoursesAndSessionsCatalog::PAGE_LENGTH;
return [
'start' => ($pageCurrent - 1) * $pageLength,
'current' => $pageCurrent,
'length' => $pageLength,
];
}
/**
* Get the formatted data for sessions block to be displayed on Session Catalog page.
*
* @param array $sessions The session list
*
* @return array
*/
private function getFormattedSessionsBlock(array $sessions)
{
$extraFieldValue = new ExtraFieldValue('session');
$userId = api_get_user_id();
$sessionsBlocks = [];
$entityManager = Database::getManager();
$sessionRelCourseRepo = $entityManager->getRepository('ChamiloCoreBundle:SessionRelCourse');
$extraFieldRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraField');
$extraFieldRelTagRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldRelTag');
$tagsField = $extraFieldRepo->findOneBy([
'extraFieldType' => Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE,
'variable' => 'tags',
]);
/** @var \Chamilo\CoreBundle\Entity\Session $session */
foreach ($sessions as $session) {
$sessionDates = SessionManager::parseSessionDates([
'display_start_date' => $session->getDisplayStartDate(),
'display_end_date' => $session->getDisplayEndDate(),
'access_start_date' => $session->getAccessStartDate(),
'access_end_date' => $session->getAccessEndDate(),
'coach_access_start_date' => $session->getCoachAccessStartDate(),
'coach_access_end_date' => $session->getCoachAccessEndDate(),
]);
$imageField = $extraFieldValue->get_values_by_handler_and_field_variable(
$session->getId(),
'image'
);
$sessionCourseTags = [];
if (!is_null($tagsField)) {
$sessionRelCourses = $sessionRelCourseRepo->findBy([
'session' => $session,
]);
/** @var SessionRelCourse $sessionRelCourse */
foreach ($sessionRelCourses as $sessionRelCourse) {
$courseTags = $extraFieldRelTagRepo->getTags(
$tagsField,
$sessionRelCourse->getCourse()->getId()
);
/** @var Tag $tag */
foreach ($courseTags as $tag) {
$sessionCourseTags[] = $tag->getTag();
}
}
}
if (!empty($sessionCourseTags)) {
$sessionCourseTags = array_unique($sessionCourseTags);
}
/** @var SequenceResourceRepository $repo */
$repo = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource');
$sequences = $repo->getRequirementsAndDependenciesWithinSequences(
$session->getId(),
SequenceResource::SESSION_TYPE
);
$hasRequirements = false;
foreach ($sequences as $sequence) {
if (count($sequence['requirements']) === 0) {
continue;
}
$hasRequirements = true;
break;
}
$cat = $session->getCategory();
if (empty($cat)) {
$cat = null;
$catName = '';
} else {
$catName = $cat->getName();
}
$generalCoach = $session->getGeneralCoach();
$coachId = $generalCoach ? $generalCoach->getId() : 0;
$coachName = $generalCoach ? UserManager::formatUserFullName($session->getGeneralCoach()) : '';
$actions = null;
if (api_is_platform_admin()) {
$actions = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$session->getId();
}
$plugin = \BuyCoursesPlugin::create();
$isThisSessionOnSale = $plugin->getBuyCoursePluginPrice($session);
$sessionsBlock = [
'id' => $session->getId(),
'name' => $session->getName(),
'image' => isset($imageField['value']) ? $imageField['value'] : null,
'nbr_courses' => $session->getNbrCourses(),
'nbr_users' => $session->getNbrUsers(),
'coach_id' => $coachId,
'coach_url' => $generalCoach
? api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$coachId
: '',
'coach_name' => $coachName,
'coach_avatar' => UserManager::getUserPicture(
$coachId,
USER_IMAGE_SIZE_SMALL
),
'is_subscribed' => SessionManager::isUserSubscribedAsStudent(
$session->getId(),
$userId
),
'icon' => $this->getSessionIcon($session->getName()),
'date' => $sessionDates['display'],
'price' => !empty($isThisSessionOnSale['html']) ? $isThisSessionOnSale['html'] : '',
'subscribe_button' => isset($isThisSessionOnSale['buy_button']) ? $isThisSessionOnSale['buy_button'] : $this->getRegisteredInSessionButton(
$session->getId(),
$session->getName(),
$hasRequirements
),
'show_description' => $session->getShowDescription(),
'description' => $session->getDescription(),
'category' => $catName,
'tags' => $sessionCourseTags,
'edit_actions' => $actions,
'duration' => SessionManager::getDayLeftInSession(
['id' => $session->getId(), 'duration' => $session->getDuration()],
$userId
),
];
$sessionsBlocks[] = array_merge($sessionsBlock, $sequences);
}
return $sessionsBlocks;
}
}

@ -183,8 +183,6 @@ foreach ($requirements as $sequence) {
}
}
$courseController = new CoursesController();
$template = new Template($course->getTitle(), true, true, false, true, false);
$template->assign('course', $courseItem);
$essence = Essence\Essence::instance();
@ -195,7 +193,7 @@ $template->assign('token', $token);
$template->assign('url', $urlCourse);
$template->assign(
'subscribe_button',
$courseController->getRequirements(
CoursesAndSessionsCatalog::getRequirements(
$course->getId(),
SequenceResource::COURSE_TYPE,
true,

@ -434,7 +434,6 @@ switch ($action) {
$sequenceList = $sequenceResourceRepository->checkRequirementsForUser($sequences, $type, $userId);
$allowSubscription = $sequenceResourceRepository->checkSequenceAreCompleted($sequenceList);
$courseController = new CoursesController();
$view = new Template(null, false, false, false, false, false);
$view->assign('sequences', $sequenceList);
$view->assign('sequence_type', $type);
@ -443,7 +442,7 @@ switch ($action) {
if ($allowSubscription) {
$view->assign(
'subscribe_button',
$courseController->getRegisteredInSessionButton(
CoursesAndSessionsCatalog::getRegisteredInSessionButton(
$id,
$resourceName,
false

@ -1,12 +1,16 @@
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\ExtraField;
use Doctrine\ORM\Query\Expr\Join;
use Chamilo\CoreBundle\Entity\Repository\SequenceResourceRepository;
use Chamilo\CoreBundle\Entity\SequenceResource;
use Chamilo\CoreBundle\Entity\SessionRelCourse;
use Chamilo\CoreBundle\Entity\Tag;
/**
* @todo change class name
* Class CoursesAndSessionsCatalog
*/
class CoursesAndSessionsCatalog
{
@ -880,4 +884,725 @@ class CoursesAndSessionsCatalog
return $row;
}
public static function getOptionSelect($categories, $codeType)
{
$html = '';
$html .= '<select name="category_code" onchange="submit();" class="selectpicker form-control">';
foreach ($categories as $category) {
$categoryCode = Security::remove_XSS($category['code']);
$categoryName = Security::remove_XSS($category['name']);
$countCourse = (int) $category['number_courses'];
$level = $category['level'];
if (empty($countCourse)) {
continue;
}
if ($level > 0) {
$separate = str_repeat('--', $level);
} else {
$separate = '';
}
$html .= '<option '.($categoryCode == $codeType ? 'selected="selected" ' : '')
.' value="'.$categoryCode.'">'.$separate.' '.$categoryName.' ('.$countCourse.') </option>';
}
$html .= '</select>';
return $html;
}
/**
* Display the course catalog image of a course.
*
* @param array $course
* @param bool $registeredUser
*
* @return string HTML string
*/
public static function returnThumbnail($course, $registeredUser)
{
$html = '';
$title = cut($course['title'], 70);
$linkCourse = api_get_path(WEB_PATH).'course/'.$course['real_id'].'/about';
// course path
$course_path = api_get_path(SYS_COURSE_PATH).$course['directory'];
if (file_exists($course_path.'/course-pic.png')) {
// redimensioned image 85x85
$courseMediumImage = api_get_path(WEB_COURSE_PATH).$course['directory'].'/course-pic.png';
} else {
// without picture
$courseMediumImage = Display::return_icon(
'session_default.png',
null,
null,
null,
null,
true
);
}
$html .= '<div class="image">';
$html .= '<a href="'.$linkCourse.'" title="'.$course['title'].'">'
.'<img class="img-responsive" src="'.$courseMediumImage.'" '
.'alt="'.api_htmlentities($title).'"/></a>';
$categoryTitle = isset($course['category_title']) ? $course['category_title'] : '';
if (!empty($categoryTitle)) {
$html .= '<span class="category">'.$categoryTitle.'</span>';
$html .= '<div class="cribbon"></div>';
}
$html .= '<div class="user-actions">';
$html .= CourseManager::returnDescriptionButton($course);
$html .= '</div></div>';
return $html;
}
/**
* @param array $courseInfo
*
* @return string
*/
public static function return_teacher($courseInfo)
{
$teachers = CourseManager::getTeachersFromCourse($courseInfo['real_id']);
$length = count($teachers);
if (!$length) {
return '';
}
$html = '<div class="block-author">';
if ($length > 6) {
$html .= '<a
id="plist"
data-trigger="focus"
tabindex="0" role="button"
class="btn btn-default panel_popover"
data-toggle="popover"
title="'.addslashes(get_lang('CourseTeachers')).'"
data-html="true"
>
<i class="fa fa-graduation-cap" aria-hidden="true"></i>
</a>';
$html .= '<div id="popover-content-plist" class="hide">';
foreach ($teachers as $value) {
$name = $value['firstname'].' '.$value['lastname'];
$html .= '<div class="popover-teacher">';
$html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
<img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
$html .= '<div class="teachers-details"><h5>
<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">'
.$name.'</a></h5></div>';
$html .= '</div>';
}
$html .= '</div>';
} else {
foreach ($teachers as $value) {
$name = $value['firstname'].' '.$value['lastname'];
if ($length > 2) {
$html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
<img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
} else {
$html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
<img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
$html .= '<div class="teachers-details"><h5>
<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'">'
.$name.'</a></h5><p>'.get_lang('Teacher').'</p></div>';
}
}
}
$html .= '</div>';
return $html;
}
/**
* Display the title of a course in course catalog.
*
* @param array $course
* @param bool $registeredUser
*
* @return string HTML string
*/
public static function return_title($course, $registeredUser)
{
//$linkCourse = api_get_course_url($course['code']);
$linkCourse = api_get_path(WEB_PATH).'course/'.$course['real_id'].'/about';
$html = '<div class="block-title"><h4 class="title">';
$html .= '<a title="'.$course['title'].'" href="'.$linkCourse.'">'.$course['title'].'</a>';
$html .= '</h4></div>';
if (api_get_configuration_value('hide_course_rating') === false) {
$ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
$rating = Display::return_rating_system(
'star_'.$course['real_id'],
$ajax_url.'&course_id='.$course['real_id'],
$course['point_info']
);
$html .= '<div class="ranking">'.$rating.'</div>';
}
return $html;
}
/**
* Display the already registerd text in a course in the course catalog.
*
* @param $in_status
*
* @return string HTML string
*/
public static function return_already_registered_label($in_status)
{
$icon = '<em class="fa fa-check"></em>';
$title = get_lang('YouAreATeacherOfThisCourse');
if ($in_status == 'student') {
$icon = '<em class="fa fa-check"></em>';
$title = get_lang('AlreadySubscribed');
}
$html = Display::tag(
'span',
$icon.' '.$title,
[
'id' => 'register',
'class' => 'label-subscribed text-success',
'title' => $title,
'aria-label' => $title,
]
);
return $html.PHP_EOL;
}
/**
* Display the register button of a course in the course catalog.
*
* @param $course
* @param $stok
* @param $code
* @param $search_term
*
* @return string
*/
public static function return_register_button($course, $stok, $code, $search_term)
{
$title = get_lang('Subscribe');
$action = 'subscribe_course';
if (!empty($course['registration_code'])) {
$action = 'subscribe_course_validation';
}
return Display::url(
Display::returnFontAwesomeIcon('check').' '.$title,
api_get_self().'?action='.$action.'&sec_token='.$stok.
'&course_code='.$course['code'].'&search_term='.$search_term.'&category_code='.$code,
['class' => 'btn btn-success btn-sm', 'title' => $title, 'aria-label' => $title]
);
}
/**
* Display the unregister button of a course in the course catalog.
*
* @param $course
* @param $stok
* @param $search_term
* @param $code
*
* @return string
*/
public static function return_unregister_button($course, $stok, $search_term, $code)
{
$title = get_lang('Unsubscription');
return Display::url(
Display::returnFontAwesomeIcon('sign-in').' '.$title,
api_get_self().'?action=unsubscribe&sec_token='.$stok
.'&course_code='.$course['code'].'&search_term='.$search_term.'&category_code='.$code,
['class' => 'btn btn-danger btn-sm', 'title' => $title, 'aria-label' => $title]
);
}
/**
* Get a HTML button for subscribe to session.
*
* @param int $sessionId The session ID
* @param string $sessionName The session name
* @param bool $checkRequirements Optional.
* Whether the session has requirement. Default is false
* @param bool $includeText Optional. Whether show the text in button
* @param bool $btnBing
*
* @return string The button HTML
*/
public static function getRegisteredInSessionButton(
$sessionId,
$sessionName,
$checkRequirements = false,
$includeText = false,
$btnBing = false
) {
$sessionId = (int) $sessionId;
if ($btnBing) {
$btnBing = 'btn-lg btn-block';
} else {
$btnBing = 'btn-sm';
}
if ($checkRequirements) {
return self::getRequirements($sessionId, SequenceResource::SESSION_TYPE, $includeText, $btnBing);
}
$catalogSessionAutoSubscriptionAllowed = false;
if (api_get_setting('catalog_allow_session_auto_subscription') === 'true') {
$catalogSessionAutoSubscriptionAllowed = true;
}
$url = api_get_path(WEB_CODE_PATH);
if ($catalogSessionAutoSubscriptionAllowed) {
$url .= 'auth/courses.php?';
$url .= http_build_query([
'action' => 'subscribe_to_session',
'session_id' => $sessionId,
]);
$result = Display::toolbarButton(
get_lang('Subscribe'),
$url,
'pencil',
'primary',
[
'class' => $btnBing.' ajax',
'data-title' => get_lang('AreYouSureToSubscribe'),
'data-size' => 'md',
'title' => get_lang('Subscribe'),
],
$includeText
);
} else {
$url .= 'inc/email_editor.php?';
$url .= http_build_query([
'action' => 'subscribe_me_to_session',
'session' => Security::remove_XSS($sessionName),
]);
$result = Display::toolbarButton(
get_lang('SubscribeToSessionRequest'),
$url,
'pencil',
'primary',
['class' => $btnBing],
$includeText
);
}
$hook = HookResubscribe::create();
if (!empty($hook)) {
$hook->setEventData([
'session_id' => $sessionId,
]);
try {
$hook->notifyResubscribe(HOOK_EVENT_TYPE_PRE);
} catch (Exception $exception) {
$result = $exception->getMessage();
}
}
return $result;
}
public static function getRequirements($id, $type, $includeText, $btnBing)
{
$id = (int) $id;
$type = (int) $type;
$url = api_get_path(WEB_AJAX_PATH);
$url .= 'sequence.ajax.php?';
$url .= http_build_query(
[
'a' => 'get_requirements',
'id' => $id,
'type' => $type,
]
);
return Display::toolbarButton(
get_lang('CheckRequirements'),
$url,
'shield',
'info',
[
'class' => $btnBing.' ajax',
'data-title' => get_lang('CheckRequirements'),
'data-size' => 'md',
'title' => get_lang('CheckRequirements'),
],
$includeText
);
}
/**
* Generate a label if the user has been registered in session.
*
* @return string The label
*/
public static function getAlreadyRegisteredInSessionLabel()
{
$icon = '<em class="fa fa-graduation-cap"></em>';
return Display::div(
$icon,
[
'class' => 'btn btn-default btn-sm registered',
'title' => get_lang("AlreadyRegisteredToSession"),
]
);
}
/**
* Get a icon for a session.
*
* @param string $sessionName The session name
*
* @return string The icon
*/
public static function getSessionIcon($sessionName)
{
return Display::return_icon(
'window_list.png',
$sessionName,
null,
ICON_SIZE_MEDIUM
);
}
/**
* Return Session catalog rendered view.
*
* @param array $limit
*/
public static function sessionList($limit = [])
{
$date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
$hiddenLinks = isset($_GET['hidden_links']) ? $_GET['hidden_links'] == 1 : false;
$limit = isset($limit) ? $limit : self::getLimitArray();
$countSessions = self::browseSessions($date, [], false, true);
$sessions = self::browseSessions($date, $limit);
$pageTotal = ceil($countSessions / $limit['length']);
// Do NOT show pagination if only one page or less
$pagination = $pageTotal > 1 ? CourseCategory::getCatalogPagination($limit['current'], $limit['length'], $pageTotal) : '';
$sessionsBlocks = self::getFormattedSessionsBlock($sessions);
// Get session search catalogue URL
$courseUrl = CourseCategory::getCourseCategoryUrl(
1,
$limit['length'],
null,
0,
'subscribe'
);
$tpl = new Template();
$tpl->assign('actions', self::getTabList(2));
$tpl->assign('show_courses', self::showCourses());
$tpl->assign('show_sessions', self::showSessions());
$tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true');
$tpl->assign('course_url', $courseUrl);
$tpl->assign('catalog_pagination', $pagination);
$tpl->assign('hidden_links', $hiddenLinks);
$tpl->assign('search_token', Security::get_token());
$tpl->assign('search_date', $date);
$tpl->assign('web_session_courses_ajax_url', api_get_path(WEB_AJAX_PATH).'course.ajax.php');
$tpl->assign('sessions', $sessionsBlocks);
$tpl->assign('already_subscribed_label', self::getAlreadyRegisteredInSessionLabel());
$tpl->assign('catalog_settings', self::getCatalogSearchSettings());
$contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
$tpl->display($contentTemplate);
}
/**
* Show the Session Catalogue with filtered session by course tags.
*
* @param array $limit Limit info
*/
public static function sessionsListByName(array $limit)
{
$keyword = isset($_POST['keyword']) ? $_POST['keyword'] : null;
$hiddenLinks = isset($_GET['hidden_links']) ? (int) $_GET['hidden_links'] == 1 : false;
$courseUrl = CourseCategory::getCourseCategoryUrl(
1,
$limit['length'],
null,
0,
'subscribe'
);
$sessions = self::getSessionsByName($keyword, $limit);
$sessionsBlocks = self::getFormattedSessionsBlock($sessions);
$tpl = new Template();
$tpl->assign('actions', self::getTabList(2));
$tpl->assign('show_courses', self::showCourses());
$tpl->assign('show_sessions', self::showSessions());
$tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true' ? true : false);
$tpl->assign('course_url', $courseUrl);
$tpl->assign('already_subscribed_label', self::getAlreadyRegisteredInSessionLabel());
$tpl->assign('hidden_links', $hiddenLinks);
$tpl->assign('search_token', Security::get_token());
$tpl->assign('keyword', Security::remove_XSS($keyword));
$tpl->assign('sessions', $sessionsBlocks);
$tpl->assign('catalog_settings', self::getCatalogSearchSettings());
$contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
$tpl->display($contentTemplate);
}
public static function getCatalogSearchSettings()
{
$settings = api_get_configuration_value('catalog_settings');
if (empty($settings)) {
// Default everything is visible
$settings = [
'sessions' => [
'by_title' => true,
'by_date' => true,
'by_tag' => true,
'show_session_info' => true,
'show_session_date' => true,
],
];
}
return $settings;
}
/**
* @param int $active
*
* @return string
*/
public static function getTabList($active = 1)
{
$pageLength = isset($_GET['pageLength']) ? (int) $_GET['pageLength'] : self::PAGE_LENGTH;
$url = CourseCategory::getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions');
$headers = [];
if (self::showCourses()) {
$headers[] = [
'url' => api_get_self(),
'content' => get_lang('CourseManagement'),
];
}
if (self::showSessions()) {
$headers[] = [
'url' => $url,
'content' => get_lang('SessionList'),
];
}
return Display::tabsOnlyLink($headers, $active);
}
/**
* Show the Session Catalogue with filtered session by course tags.
*
* @param array $limit Limit info
*/
public static function sessionsListByCoursesTag(array $limit)
{
$searchTag = isset($_POST['search_tag']) ? $_POST['search_tag'] : null;
$searchDate = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
$hiddenLinks = isset($_GET['hidden_links']) ? (int) $_GET['hidden_links'] == 1 : false;
$courseUrl = CourseCategory::getCourseCategoryUrl(
1,
$limit['length'],
null,
0,
'subscribe'
);
$sessions = self::browseSessionsByTags($searchTag, $limit);
$sessionsBlocks = self::getFormattedSessionsBlock($sessions);
$tpl = new Template();
$tpl->assign('show_courses', self::showCourses());
$tpl->assign('show_sessions', self::showSessions());
$tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true' ? true : false);
$tpl->assign('course_url', $courseUrl);
$tpl->assign('already_subscribed_label', self::getAlreadyRegisteredInSessionLabel());
$tpl->assign('hidden_links', $hiddenLinks);
$tpl->assign('search_token', Security::get_token());
$tpl->assign('search_date', Security::remove_XSS($searchDate));
$tpl->assign('search_tag', Security::remove_XSS($searchTag));
$tpl->assign('sessions', $sessionsBlocks);
$contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
$tpl->display($contentTemplate);
}
/**
* @return array
*/
public static function getLimitArray()
{
$pageCurrent = isset($_REQUEST['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
$pageLength = isset($_REQUEST['pageLength']) ? (int) $_GET['pageLength'] : self::PAGE_LENGTH;
return [
'start' => ($pageCurrent - 1) * $pageLength,
'current' => $pageCurrent,
'length' => $pageLength,
];
}
/**
* Get the formatted data for sessions block to be displayed on Session Catalog page.
*
* @param array $sessions The session list
*
* @return array
*/
public static function getFormattedSessionsBlock(array $sessions)
{
$extraFieldValue = new ExtraFieldValue('session');
$userId = api_get_user_id();
$sessionsBlocks = [];
$entityManager = Database::getManager();
$sessionRelCourseRepo = $entityManager->getRepository('ChamiloCoreBundle:SessionRelCourse');
$extraFieldRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraField');
$extraFieldRelTagRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldRelTag');
$tagsField = $extraFieldRepo->findOneBy([
'extraFieldType' => Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE,
'variable' => 'tags',
]);
/** @var \Chamilo\CoreBundle\Entity\Session $session */
foreach ($sessions as $session) {
$sessionDates = SessionManager::parseSessionDates([
'display_start_date' => $session->getDisplayStartDate(),
'display_end_date' => $session->getDisplayEndDate(),
'access_start_date' => $session->getAccessStartDate(),
'access_end_date' => $session->getAccessEndDate(),
'coach_access_start_date' => $session->getCoachAccessStartDate(),
'coach_access_end_date' => $session->getCoachAccessEndDate(),
]);
$imageField = $extraFieldValue->get_values_by_handler_and_field_variable(
$session->getId(),
'image'
);
$sessionCourseTags = [];
if (!is_null($tagsField)) {
$sessionRelCourses = $sessionRelCourseRepo->findBy([
'session' => $session,
]);
/** @var SessionRelCourse $sessionRelCourse */
foreach ($sessionRelCourses as $sessionRelCourse) {
$courseTags = $extraFieldRelTagRepo->getTags(
$tagsField,
$sessionRelCourse->getCourse()->getId()
);
/** @var Tag $tag */
foreach ($courseTags as $tag) {
$sessionCourseTags[] = $tag->getTag();
}
}
}
if (!empty($sessionCourseTags)) {
$sessionCourseTags = array_unique($sessionCourseTags);
}
/** @var SequenceResourceRepository $repo */
$repo = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource');
$sequences = $repo->getRequirementsAndDependenciesWithinSequences(
$session->getId(),
SequenceResource::SESSION_TYPE
);
$hasRequirements = false;
foreach ($sequences as $sequence) {
if (count($sequence['requirements']) === 0) {
continue;
}
$hasRequirements = true;
break;
}
$cat = $session->getCategory();
if (empty($cat)) {
$cat = null;
$catName = '';
} else {
$catName = $cat->getName();
}
$generalCoach = $session->getGeneralCoach();
$coachId = $generalCoach ? $generalCoach->getId() : 0;
$coachName = $generalCoach ? UserManager::formatUserFullName($session->getGeneralCoach()) : '';
$actions = null;
if (api_is_platform_admin()) {
$actions = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$session->getId();
}
$plugin = \BuyCoursesPlugin::create();
$isThisSessionOnSale = $plugin->getBuyCoursePluginPrice($session);
$sessionsBlock = [
'id' => $session->getId(),
'name' => $session->getName(),
'image' => isset($imageField['value']) ? $imageField['value'] : null,
'nbr_courses' => $session->getNbrCourses(),
'nbr_users' => $session->getNbrUsers(),
'coach_id' => $coachId,
'coach_url' => $generalCoach
? api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$coachId
: '',
'coach_name' => $coachName,
'coach_avatar' => UserManager::getUserPicture(
$coachId,
USER_IMAGE_SIZE_SMALL
),
'is_subscribed' => SessionManager::isUserSubscribedAsStudent(
$session->getId(),
$userId
),
'icon' => self::getSessionIcon($session->getName()),
'date' => $sessionDates['display'],
'price' => !empty($isThisSessionOnSale['html']) ? $isThisSessionOnSale['html'] : '',
'subscribe_button' => isset($isThisSessionOnSale['buy_button']) ? $isThisSessionOnSale['buy_button'] : self::getRegisteredInSessionButton(
$session->getId(),
$session->getName(),
$hasRequirements
),
'show_description' => $session->getShowDescription(),
'description' => $session->getDescription(),
'category' => $catName,
'tags' => $sessionCourseTags,
'edit_actions' => $actions,
'duration' => SessionManager::getDayLeftInSession(
['id' => $session->getId(), 'duration' => $session->getDuration()],
$userId
),
];
$sessionsBlocks[] = array_merge($sessionsBlock, $sequences);
}
return $sessionsBlocks;
}
}

@ -1,4 +1,5 @@
<?php
/* For licensing terms, see /license.txt */
/**
@ -9,8 +10,7 @@
*
* @author Christian Fasanando <christian1827@gmail.com>
*
* @package chamilo.auth
*/
**/
class Auth
{
/**
@ -53,7 +53,7 @@ class Auth
WHERE
course.id = course_rel_user.c_id AND
course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
course_rel_user.user_id = '".$user_id."'
course_rel_user.user_id = '".$user_id."'
$avoidCoursesCondition
$visibilityCondition
ORDER BY course_rel_user.sort ASC";
@ -262,11 +262,11 @@ class Auth
$result = false;
if (count($target_category) > 0 && count($source_category) > 0) {
$table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
$sql = "UPDATE $table SET
$sql = "UPDATE $table SET
sort = '".Database::escape_string($target_category['sort'])."'
WHERE id='".intval($source_category['id'])."' AND user_id='".$userId."'";
$resultFirst = Database::query($sql);
$sql = "UPDATE $table SET
$sql = "UPDATE $table SET
sort = '".Database::escape_string($source_category['sort'])."'
WHERE id='".intval($target_category['id'])."' AND user_id='".$userId."'";
$resultSecond = Database::query($sql);
@ -288,7 +288,6 @@ class Auth
*/
public function store_edit_course_category($title, $category_id)
{
// protect data
$title = Database::escape_string($title);
$category_id = (int) $category_id;
$result = false;
@ -319,8 +318,8 @@ class Auth
$category_id = (int) $category_id;
$result = false;
$sql = "DELETE FROM $tucc
WHERE
id='".$category_id."' AND
WHERE
id='".$category_id."' AND
user_id='".$current_user_id."'";
$resultQuery = Database::query($sql);
if (Database::affected_rows($resultQuery)) {
@ -349,13 +348,12 @@ class Auth
$categoryId = (int) $categoryId;
$sql = "SELECT * FROM $tucc
WHERE
id= $categoryId AND
WHERE
id= $categoryId AND
user_id= $userId";
$resultQuery = Database::query($sql);
$result = Database::fetch_array($resultQuery, 'ASSOC');
return $result;
return Database::fetch_array($resultQuery, 'ASSOC');
}
/**
@ -413,8 +411,8 @@ class Auth
$result = false;
// step 1: we determine the max value of the user defined course categories
$sql = "SELECT sort FROM $table
WHERE user_id='".$current_user_id."'
$sql = "SELECT sort FROM $table
WHERE user_id='".$current_user_id."'
ORDER BY sort DESC";
$rs_sort = Database::query($sql);
$maxsort = Database::fetch_array($rs_sort);
@ -422,9 +420,9 @@ class Auth
// step 2: we check if there is already a category with this name,
// if not we store it, else we give an error.
$sql = "SELECT * FROM $table
WHERE
user_id='".$current_user_id."' AND
$sql = "SELECT * FROM $table
WHERE
user_id='".$current_user_id."' AND
title='".$category_title."'
ORDER BY sort DESC";
$rs = Database::query($sql);

@ -3971,7 +3971,6 @@ class CourseManager
$courseAdded = [];
$courseList = [];
$courseController = new CoursesController();
while ($row = Database::fetch_array($result)) {
$course_info = api_get_course_info_by_id($row['id']);
if (empty($course_info)) {
@ -4320,9 +4319,6 @@ class CourseManager
);
}
$params['link'] = $session_url;
$courseController = new CoursesController();
$entityManager = Database::getManager();
/** @var SequenceResourceRepository $repo */
$repo = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource');
@ -4343,7 +4339,7 @@ class CourseManager
}
}
if ($hasRequirements) {
$params['requirements'] = $courseController->getRequirements(
$params['requirements'] = CoursesAndSessionsCatalog::getRequirements(
$course_info['real_id'],
SequenceResource::COURSE_TYPE,
false,

@ -743,10 +743,12 @@ class CourseCategory
* @param $pageCurrent
* @param $pageLength
* @param $pageTotal
* @param $categoryCode
* @param $action
*
* @return string
*/
public static function getCatalogPagination($pageCurrent, $pageLength, $pageTotal)
public static function getCatalogPagination($pageCurrent, $pageLength, $pageTotal, $categoryCode = '', $action = '')
{
// Start empty html
$pageDiv = '';
@ -761,7 +763,9 @@ class CourseCategory
$pageBottom - 1,
$pageLength,
null,
'...'
'...',
$categoryCode,
$action
);
}
}
@ -776,7 +780,10 @@ class CourseCategory
$pageDiv .= self::getPageNumberItem(
$i,
$pageLength,
$pageItemAttributes
$pageItemAttributes,
'',
$categoryCode,
$action
);
}
@ -787,10 +794,12 @@ class CourseCategory
$pageTop + 1,
$pageLength,
null,
'...'
'...',
$categoryCode,
$action
);
}
$pageDiv .= self::getPageNumberItem($pageTotal, $pageLength);
$pageDiv .= self::getPageNumberItem($pageTotal, $pageLength,[], '', $categoryCode, $action);
}
// Complete pagination html
@ -827,9 +836,9 @@ class CourseCategory
}
$categoryCodeRequest = isset($_REQUEST['category_code']) ? Security::remove_XSS($_REQUEST['category_code']) : null;
$categoryCode = isset($categoryCode) ? Security::remove_XSS($categoryCode) : $categoryCodeRequest;
$hiddenLinksRequest = isset($_REQUEST['hidden_links']) ? Security::remove_XSS($_REQUEST['hidden_links']) : null;
$hiddenLinks = isset($hiddenLinks) ? Security::remove_XSS($hiddenLinksRequest) : $categoryCodeRequest;
$categoryCode = !empty($categoryCode) ? Security::remove_XSS($categoryCode) : $categoryCodeRequest;
$hiddenLinksRequest = !empty($_REQUEST['hidden_links']) ? Security::remove_XSS($_REQUEST['hidden_links']) : null;
$hiddenLinks = !empty($hiddenLinks) ? Security::remove_XSS($hiddenLinksRequest) : $categoryCodeRequest;
// Start URL with params
$pageUrl = api_get_self().
@ -869,13 +878,12 @@ class CourseCategory
$pageNumber,
$pageLength,
$liAttributes = [],
$content = ''
$content = '',
$categoryCode = '',
$action = ''
) {
// Get page URL
$url = self::getCourseCategoryUrl(
$pageNumber,
$pageLength
);
$url = self::getCourseCategoryUrl($pageNumber, $pageLength, $categoryCode, null, $action);
// If is current page ('active' class) clear URL
if (isset($liAttributes) && is_array($liAttributes) && isset($liAttributes['class'])) {

@ -614,7 +614,7 @@ class IndexManager
// 2.
if ($user_identified && !array_key_exists($course['code'], $courses_of_user)) {
if ($course['subscribe'] == '1') {
$courses_list_string .= '&nbsp;<a class="btn btn-primary" href="main/auth/courses.php?action=subscribe_course&sec_token='.$stok.'&subscribe_course='.$course['code'].'&category_code='.Security::remove_XSS(
$courses_list_string .= '&nbsp;<a class="btn btn-primary" href="main/auth/courses.php?action=subscribe_course&sec_token='.$stok.'&course_code='.$course['code'].'&category_code='.Security::remove_XSS(
$_GET['category']
).'">'.get_lang('Subscribe').'</a><br />';
} else {

@ -168,8 +168,6 @@ foreach ($requirements as $sequence) {
}
}
$courseController = new CoursesController();
/* View */
$template = new Template($session->getName(), true, true, false, true, false);
$template->assign('show_tutor', ('true' === api_get_setting('show_session_coach') ? true : false));
@ -185,7 +183,7 @@ $template->assign(
);
$template->assign(
'subscribe_button',
$courseController->getRegisteredInSessionButton(
CoursesAndSessionsCatalog::getRegisteredInSessionButton(
$session->getId(),
$session->getName(),
$hasRequirements,

@ -20,7 +20,7 @@
<form onSubmit="$(this).toggle('slow')" action="" method="post">
<input value=1 type="hidden" name="acceptCookies"/>
<div class="cookieUsageValidation">
{{ "YouAcceptCookies" | get_lang }}
{{ 'YouAcceptCookies' | get_lang }}
<span style="margin-left:20px;" onclick="$(this).next().toggle('slow'); $(this).toggle('slow')">
({{"More" | get_lang }})
</span>

@ -20,7 +20,7 @@
<form onSubmit="$(this).toggle('slow')" action="" method="post">
<input value=1 type="hidden" name="acceptCookies"/>
<div class="cookieUsageValidation">
{{ "YouAcceptCookies" | get_lang }}
{{ 'YouAcceptCookies' | get_lang }}
<span style="margin-left:20px;" onclick="$(this).next().toggle('slow'); $(this).toggle('slow')">
({{"More" | get_lang }})
</span>

Loading…
Cancel
Save