Move code to function

pull/3951/head
Angel Fernando Quiroz Campos 4 years ago
parent d62bb55eed
commit a0f952ccb3
  1. 62
      main/auth/courses.php
  2. 37
      main/course_home/course_home.php
  3. 108
      main/inc/lib/course.lib.php

@ -90,6 +90,23 @@ if (!empty($settings)) {
} }
} }
function generateRedirectUrlAfterSubscription($redirectAfterSubscription, $coursePublicUrl): string
{
if ('course_home' !== $redirectAfterSubscription) {
return api_get_self();
}
if (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) {
$user = api_get_user_entity(api_get_user_id());
if ($user && $accesibleSessions = $user->getCurrentlyAccessibleSessions()) {
return $coursePublicUrl.'?id_session='.$accesibleSessions[0]->getId();
}
}
return $coursePublicUrl;
}
switch ($action) { switch ($action) {
case 'unsubscribe': case 'unsubscribe':
// We are unsubscribing from a course (=Unsubscribe from course). // We are unsubscribing from a course (=Unsubscribe from course).
@ -114,22 +131,12 @@ switch ($action) {
if (Security::check_token('get')) { if (Security::check_token('get')) {
$courseInfo = api_get_course_info($courseCodeToSubscribe); $courseInfo = api_get_course_info($courseCodeToSubscribe);
CourseManager::autoSubscribeToCourse($courseCodeToSubscribe); CourseManager::autoSubscribeToCourse($courseCodeToSubscribe);
if ('course_home' === $redirectAfterSubscription) { $redirectionTarget = generateRedirectUrlAfterSubscription(
$redirectionTarget = $courseInfo['course_public_url']; $redirectAfterSubscription,
if (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) { $courseInfo['course_public_url']
$user = api_get_user_entity(api_get_user_id()); );
if ($user) {
foreach ($user->getCurrentlyAccessibleSessions() as $session) {
$redirectionTarget = $redirectionTarget.'?id_session='.$session->getId();
break;
}
}
}
header('Location: '.$redirectionTarget);
exit; header("Location: $redirectionTarget");
}
header('Location: '.api_get_self());
exit; exit;
} }
break; break;
@ -162,28 +169,17 @@ switch ($action) {
if (sha1($_POST['course_registration_code']) === $courseInfo['registration_code']) { if (sha1($_POST['course_registration_code']) === $courseInfo['registration_code']) {
CourseManager::autoSubscribeToCourse($_POST['subscribe_user_with_password']); CourseManager::autoSubscribeToCourse($_POST['subscribe_user_with_password']);
if ('course_home' === $redirectAfterSubscription) { $redirectionTarget = generateRedirectUrlAfterSubscription(
$redirectionTarget = $courseInfo['course_public_url']; $redirectAfterSubscription,
if (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) { $courseInfo['course_public_url']
$user = api_get_user_entity(api_get_user_id()); );
if ($user) {
foreach ($user->getCurrentlyAccessibleSessions() as $session) {
$redirectionTarget = $redirectionTarget.'?id_session='.$session->getId();
break;
}
}
}
header('Location: '.$redirectionTarget);
exit;
}
header('Location: '.api_get_self()); header("Location: $redirectionTarget");
exit;
} else { } else {
Display::addFlash(Display::return_message(get_lang('CourseRegistrationCodeIncorrect')), 'warning'); Display::addFlash(Display::return_message(get_lang('CourseRegistrationCodeIncorrect'), 'warning'));
header('Location: '.$action); header('Location: '.$action);
exit;
} }
exit;
} }
break; break;

@ -229,40 +229,35 @@ if ($isSpecialCourse) {
$action = !empty($_GET['action']) ? Security::remove_XSS($_GET['action']) : ''; $action = !empty($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
if ($action === 'subscribe') { if ($action === 'subscribe' && Security::check_token('get')) {
if (Security::check_token('get')) { Security::clear_token();
Security::clear_token(); $generateRedirectUrlAfterSubscription = function () use ($course_code, $courseId, $user_id) {
$redirectionTarget = api_get_self(); $redirectionTarget = api_get_self();
if (CourseManager::autoSubscribeToCourse($course_code)) { if (CourseManager::autoSubscribeToCourse($course_code)) {
if (CourseManager::is_user_subscribed_in_course($user_id, $course_code)) { if (CourseManager::is_user_subscribed_in_course($user_id, $course_code)) {
Session::write('is_allowed_in_course', true); Session::write('is_allowed_in_course', true);
} }
if (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) { if (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) {
// append session id to redirect URL $user = api_get_user_entity(api_get_user_id());
/**
* @var Chamilo\UserBundle\Entity\User if ($user && $accesibleSessions = $user->getCurrentlyAccessibleSessions()) {
*/ return api_get_self().'?id_session='.$accesibleSessions[0]->getId();
$user = UserManager::getRepository()->find(api_get_user_id());
if ($user) {
foreach ($user->getCurrentlyAccessibleSessions() as $session) {
$redirectionTarget = api_get_self().'?id_session='.$session->getId();
break;
}
} }
} }
} elseif (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) { } elseif (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) {
/** $user = api_get_user_entity(api_get_user_id());
* @var Chamilo\UserBundle\Entity\User
*/
$user = UserManager::getRepository()->find(api_get_user_id());
if ($user && !$user->getCurrentlyAccessibleSessions()) { if ($user && !$user->getCurrentlyAccessibleSessions()) {
// subscription was probably refused because user session expired, go back to page "about" // subscription was probably refused because user session expired, go back to page "about"
$redirectionTarget = api_get_path(WEB_PATH).'course/'.$courseId.'/about'; return api_get_path(WEB_PATH).'course/'.$courseId.'/about';
} }
} }
header('Location: '.$redirectionTarget);
exit; return $redirectionTarget;
} };
header('Location: '.$generateRedirectUrlAfterSubscription());
exit;
} }
/* Is the user allowed here? */ /* Is the user allowed here? */

@ -618,86 +618,50 @@ class CourseManager
} }
/** /**
* @param string $courseCode * @throws Exception
* @param int $status
*
* @return bool
*/ */
public static function autoSubscribeToCourse($courseCode, $status = STUDENT) public static function processAutoSubscribeToCourse(string $courseCode, int $status = STUDENT)
{ {
if (api_is_anonymous()) { if (api_is_anonymous()) {
return false; throw new Exception(get_lang('NotAllowed'));
} }
$course = Database::getManager()->getRepository('ChamiloCoreBundle:Course')->findOneBy(['code' => $courseCode]); $course = Database::getManager()->getRepository('ChamiloCoreBundle:Course')->findOneBy(['code' => $courseCode]);
if (null === $course) { if (null === $course) {
return false; throw new Exception(get_lang('NotAllowed'));
} }
$visibility = (int) $course->getVisibility(); $visibility = (int) $course->getVisibility();
if (in_array($visibility, [ if (in_array($visibility, [COURSE_VISIBILITY_CLOSED, COURSE_VISIBILITY_HIDDEN])) {
COURSE_VISIBILITY_CLOSED, throw new Exception(get_lang('SubscribingNotAllowed'));
//COURSE_VISIBILITY_REGISTERED,
COURSE_VISIBILITY_HIDDEN,
])) {
Display::addFlash(
Display::return_message(
get_lang('SubscribingNotAllowed'),
'warning'
)
);
return false;
} }
// Private course can allow auto subscription // Private course can allow auto subscription
if (COURSE_VISIBILITY_REGISTERED === $visibility && false === $course->getSubscribe()) { if (COURSE_VISIBILITY_REGISTERED === $visibility && false === $course->getSubscribe()) {
Display::addFlash( throw new Exception(get_lang('SubscribingNotAllowed'));
Display::return_message(
get_lang('SubscribingNotAllowed'),
'warning'
)
);
return false;
} }
$userId = api_get_user_id(); $userId = api_get_user_id();
if (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) { if (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) {
/** $user = api_get_user_entity($userId);
* @var Chamilo\UserBundle\Entity\User
*/
$user = UserManager::getRepository()->find($userId);
$sessions = $user->getCurrentlyAccessibleSessions(); $sessions = $user->getCurrentlyAccessibleSessions();
if (empty($sessions)) { if (empty($sessions)) {
// user has no accessible session // user has no accessible session
if ($user->getStudentSessions()) { if ($user->getStudentSessions()) {
// user has ancient or future student session(s) but not available now // user has ancient or future student session(s) but not available now
Display::addFlash( throw new Exception(get_lang('CanNotSubscribeToCourseUserSessionExpired'));
Display::return_message(
get_lang('CanNotSubscribeToCourseUserSessionExpired'),
'warning'
)
);
return false;
} }
// user has no session at all, create one starting now // user has no session at all, create one starting now
$numberOfDays = api_get_configuration_value('user_s_session_duration') ?: 3 * 365; $numberOfDays = api_get_configuration_value('user_s_session_duration') ?: 3 * 365;
try { try {
$duration = new DateInterval(sprintf('P%dD', $numberOfDays)); $duration = new DateInterval(sprintf('P%dD', $numberOfDays));
} catch (Exception $exception) { } catch (Exception $exception) {
Display::addFlash( throw new Exception(
Display::return_message( get_lang('WrongNumberOfDays').': '.$numberOfDays.': '.$exception->getMessage()
get_lang('WrongNumberOfDays').': '.$numberOfDays.': '.$exception->getMessage(),
'warning'
)
); );
return false;
} }
$endDate = new DateTime(); $endDate = new DateTime();
$endDate->add($duration); $endDate->add($duration);
@ -715,14 +679,9 @@ class CourseManager
try { try {
Database::getManager()->flush(); Database::getManager()->flush();
} catch (\Doctrine\ORM\OptimisticLockException $exception) { } catch (\Doctrine\ORM\OptimisticLockException $exception) {
Display::addFlash( throw new Exception(
Display::return_message( get_lang('InternalDatabaseError').': '.$exception->getMessage()
get_lang('InternalDatabaseError').': '.$exception->getMessage(),
'warning'
)
); );
return false;
} }
$accessUrlRelSession = new \Chamilo\CoreBundle\Entity\AccessUrlRelSession(); $accessUrlRelSession = new \Chamilo\CoreBundle\Entity\AccessUrlRelSession();
$accessUrlRelSession->setAccessUrlId(api_get_current_access_url_id()); $accessUrlRelSession->setAccessUrlId(api_get_current_access_url_id());
@ -731,14 +690,9 @@ class CourseManager
try { try {
Database::getManager()->flush(); Database::getManager()->flush();
} catch (\Doctrine\ORM\OptimisticLockException $exception) { } catch (\Doctrine\ORM\OptimisticLockException $exception) {
Display::addFlash( throw new Exception(
Display::return_message( get_lang('InternalDatabaseError').': '.$exception->getMessage()
get_lang('InternalDatabaseError').': '.$exception->getMessage(),
'warning'
)
); );
return false;
} }
} else { } else {
// user has at least one accessible session, let's use it // user has at least one accessible session, let's use it
@ -750,22 +704,36 @@ class CourseManager
try { try {
Database::getManager()->flush(); Database::getManager()->flush();
} catch (\Doctrine\ORM\OptimisticLockException $exception) { } catch (\Doctrine\ORM\OptimisticLockException $exception) {
Display::addFlash( throw new Exception(
Display::return_message( get_lang('InternalDatabaseError').': '.$exception->getMessage()
get_lang('InternalDatabaseError').': '.$exception->getMessage(),
'warning'
)
); );
return false;
} }
// subscribe user to course within this session // subscribe user to course within this session
SessionManager::subscribe_users_to_session_course([$userId], $session->getId(), $course->getCode()); SessionManager::subscribe_users_to_session_course([$userId], $session->getId(), $course->getCode());
}
return true; self::subscribeUser($userId, $course->getCode(), $status, 0);
}
/**
* @param string $courseCode
* @param int $status
*
* @return bool
*/
public static function autoSubscribeToCourse($courseCode, $status = STUDENT): bool
{
try {
self::processAutoSubscribeToCourse($courseCode, $status);
} catch (Exception $e) {
Display::addFlash(
Display::return_message($e->getMessage(), 'warning')
);
return false;
} }
return self::subscribeUser($userId, $course->getCode(), $status, 0); return true;
} }
/** /**

Loading…
Cancel
Save