Update code from 1.11.x

Use FormValidator in add_users_to_session.php + remove xajax
pull/3890/head
Julio Montoya 4 years ago
parent a0a4816858
commit e98a669d29
  1. 140
      public/main/inc/lib/sessionmanager.lib.php
  2. 374
      public/main/session/add_courses_to_session.php
  3. 1
      public/main/session/add_users_to_session.php
  4. 4
      public/main/session/resume_session.php
  5. 1
      public/main/session/session_course_edit.php
  6. 7
      tests/behat/features/sessionAccess.feature

@ -17,8 +17,6 @@ use ExtraField as ExtraFieldModel;
use Monolog\Logger;
/**
* Class SessionManager.
*
* This is the session library for Chamilo
* (as in courses>session, not as in PHP session)
* All main sessions functions should be placed here.
@ -38,9 +36,6 @@ class SessionManager
public const SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION = 4;
public const DEFAULT_VISIBILITY = 4; //SESSION_AVAILABLE
/**
* Constructor.
*/
public function __construct()
{
}
@ -54,8 +49,6 @@ class SessionManager
*/
public static function fetch($id)
{
$em = Database::getManager();
if (empty($id)) {
return [];
}
@ -2057,51 +2050,22 @@ class SessionManager
}
}
// Replace with this new function
// insert new users into session_rel_course_rel_user and ignore if they already exist
foreach ($userList as $enreg_user) {
if (!in_array($enreg_user, $existingUsers)) {
$status = self::get_user_status_in_course_session(
$enreg_user,
$courseId,
$sessionId
);
// Avoid duplicate entries.
if (false === $status || (false !== $status && 0 != $status)) {
$enreg_user = (int) $enreg_user;
$sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility, status)
VALUES($sessionId, $courseId, $enreg_user, $session_visibility, 0)";
$result = Database::query($sql);
if (Database::affected_rows($result)) {
$nbr_users++;
$usersToSubscribeInCourse = array_filter(
$userList,
function ($userId) use ($existingUsers) {
return !in_array($userId, $existingUsers);
}
);
Event::addEvent(
LOG_SESSION_ADD_USER_COURSE,
LOG_USER_ID,
$enreg_user,
api_get_utc_datetime(),
api_get_user_id(),
self::insertUsersInCourse(
$usersToSubscribeInCourse,
$courseId,
$sessionId
$sessionId,
['visibility' => $session_visibility],
false
);
}
}
}
// Count users in this session-course relation
$sql = "SELECT COUNT(user_id) as nbUsers
FROM $tbl_session_rel_course_rel_user
WHERE session_id = $sessionId AND c_id = $courseId AND status<>2";
$rs = Database::query($sql);
[$nbr_users] = Database::fetch_array($rs);
// update the session-course relation to add the users total
$sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users
WHERE session_id = $sessionId AND c_id = $courseId";
Database::query($sql);
}
}
// Delete users from the session
if (true === $empty_users) {
@ -9638,15 +9602,32 @@ class SessionManager
foreach ($studentIds as $studentId) {
$sessionCourseUser['user_id'] = $studentId;
$count = Database::select(
'COUNT(1) as nbr',
$tblSessionCourseUser,
['where' => ['session_id = ? AND c_id = ? AND user_id = ?' => [$sessionId, $courseId, $studentId]]],
'first'
);
if (empty($count['nbr'])) {
Database::insert($tblSessionCourseUser, $sessionCourseUser);
Event::logUserSubscribedInCourseSession($studentId, $courseId, $sessionId);
}
if ($updateSession) {
$sessionUser['user_id'] = $studentId;
$count = Database::select(
'COUNT(1) as nbr',
$tblSessionUser,
['where' => ['session_id = ? AND user_id = ?' => [$sessionId, $studentId]]],
'first'
);
if (empty($count['nbr'])) {
Database::insert($tblSessionUser, $sessionUser);
}
Event::logUserSubscribedInCourseSession($studentId, $courseId, $sessionId);
}
}
Database::query(
@ -9671,20 +9652,18 @@ class SessionManager
}
}
public static function getCareerDiagramPerSession($sessionId, $userId): string
public static function getCareersFromSession(int $sessionId): array
{
$extraFieldValueSession = new ExtraFieldValue('session');
$extraFieldValueCareer = new ExtraFieldValue('career');
$visibility = api_get_session_visibility($sessionId, null, false, $userId);
$content = '';
if (SESSION_AVAILABLE === $visibility) {
$value = $extraFieldValueSession->get_values_by_handler_and_field_variable($sessionId, 'careerid');
$careers = [];
if (isset($value['value']) && !empty($value['value'])) {
$careerList = str_replace(['[', ']'], '', $value['value']);
$careerList = explode(',', $careerList);
$careerManager = new Career();
foreach ($careerList as $career) {
$careerIdValue = $extraFieldValueCareer->get_item_id_from_field_variable_and_field_value(
'external_career_id',
@ -9692,24 +9671,57 @@ class SessionManager
);
if (isset($careerIdValue['item_id']) && !empty($careerIdValue['item_id'])) {
$finalCareerId = $careerIdValue['item_id'];
$career = new Career();
$careerInfo = $career->get($finalCareerId);
$careerInfo = $careerManager->get($finalCareerId);
if (!empty($careerInfo)) {
$careerUrl = api_get_path(WEB_CODE_PATH).
'user/career_diagram.php?iframe=1&career_id='.$finalCareerId;
$content .= '<iframe
style="width:100%; height:500px"
border="0"
frameborder="0"
src="'.$careerUrl.'"></iframe>';
$careers[] = $careerInfo;
}
}
}
}
return $careers;
}
if (!empty($content)) {
$content = Display::page_subheader(get_lang('OngoingTraining')).$content;
public static function getCareerDiagramPerSessionList($sessionList, $userId)
{
if (empty($sessionList) || empty($userId)) {
return '';
}
$userId = (int) $userId;
$content = Display::page_subheader(get_lang('OngoingTraining'));
$content .= '
<script>
resizeIframe = function(iFrame) {
iFrame.height = iFrame.contentWindow.document.body.scrollHeight + 20;
}
</script>
';
$careersAdded = [];
foreach ($sessionList as $sessionId) {
$visibility = api_get_session_visibility($sessionId, null, false, $userId);
if (SESSION_AVAILABLE === $visibility) {
$careerList = self::getCareersFromSession($sessionId);
if (empty($careerList)) {
continue;
}
foreach ($careerList as $career) {
$careerId = $career['id'];
if (!in_array($careerId, $careersAdded)) {
$careersAdded[] = $careerId;
$careerUrl = api_get_path(WEB_CODE_PATH).'user/career_diagram.php?iframe=1&career_id='.$career['id'].'&user_id='.$userId;
$content .= '
<iframe
onload="resizeIframe(this)"
style="width:100%;"
border="0"
frameborder="0"
scrolling="no"
src="'.$careerUrl.'"
></iframe>';
}
}
}
}
return $content;

@ -2,21 +2,15 @@
/* For licensing terms, see /license.txt */
/**
* @todo use formvalidator
*/
$cidReset = true;
require_once __DIR__.'/../inc/global.inc.php';
$sessionId = isset($_GET['id_session']) ? (int) $_GET['id_session'] : 0;
$add = isset($_GET['add']) ? Security::remove_XSS($_GET['add']) : null;
$add = isset($_GET['add']) ? 1 : 0;
$session = api_get_session_entity($sessionId);
SessionManager::protectSession($session);
$xajax = new xajax();
$xajax->registerFunction(['search_courses', 'AddCourseToSession', 'search_courses']);
// Setting the section (for the tabs)
$this_section = SECTION_PLATFORM_ADMIN;
@ -30,363 +24,83 @@ $interbreadcrumb[] = [
'name' => get_lang('Session overview'),
];
// Database Table Definitions
$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
$tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
$tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
// setting the name of the tool
$tool_name = get_lang('Add courses to this session');
$add_type = 'multiple';
if (isset($_GET['add_type']) && '' != $_GET['add_type']) {
$add_type = Security::remove_XSS($_REQUEST['add_type']);
}
$page = isset($_GET['page']) ? Security::remove_XSS($_GET['page']) : null;
$xajax->processRequests();
$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
$htmlHeadXtra[] = '<script>
function add_course_to_session(code, content) {
document.getElementById("course_to_add").value = "";
document.getElementById("ajax_list_courses_single").innerHTML = "";
destination = document.getElementById("destination");
for (i=0;i<destination.length;i++) {
if (destination.options[i].text == content) {
return false;
}
}
destination.options[destination.length] = new Option(content,code);
destination.selectedIndex = -1;
sortOptions(destination.options);
}
Display::display_header($tool_name);
function remove_item(origin)
{
for(var i = 0 ; i<origin.options.length ; i++) {
if(origin.options[i].selected) {
origin.options[i]=null;
i = i-1;
}
}
}
</script>';
$form = new FormValidator(
'add_course_to_session',
'post',
api_get_self().'?id_session='.$sessionId.'&add='.$add
);
$form->addHidden('id_session', $sessionId);
$form->addHidden('add', $add);
$form->addSelectAjax(
'courses',
get_lang('Course'),
null,
[
'url' => api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=search_course',
'multiple' => 'multiple'
]
);
$CourseList = $SessionList = [];
$courses = $sessions = [];
$form->addCheckBox('copy_evaluation', null, get_lang('Import gradebook from base course'));
$form->addCheckBox(
'import_teachers_as_course_coach',
null,
get_lang('Import course teachers as course coach in the session')
);
$form->addCheckBox(
'import_assignments',
null,
get_lang('Import assignments from base course')
);
$form->addButtonSave(get_lang('Add'));
if (isset($_POST['formSent']) && $_POST['formSent'] && isset($_POST['SessionCoursesList'])) {
$courseList = $_POST['SessionCoursesList'];
$copyEvaluation = isset($_POST['copy_evaluation']);
$copyCourseTeachersAsCoach = isset($_POST['import_teachers_as_course_coach']);
$contentForm = $form->returnForm();
if ($form->validate()) {
$data = $form->getSubmitValues();
$courseList = $data['courses'];
$copyEvaluation = isset($data['copy_evaluation']);
$copyCourseTeachersAsCoach = isset($data['import_teachers_as_course_coach']);
$importAssignments = isset($data['import_assignments']);
SessionManager::add_courses_to_session(
$sessionId,
$courseList,
true,
false,
$copyEvaluation,
$copyCourseTeachersAsCoach
$copyCourseTeachersAsCoach,
$importAssignments
);
Display::addFlash(Display::return_message(get_lang('Update successful')));
$url = api_get_path(WEB_CODE_PATH).'session/';
if (isset($add)) {
if ($add) {
header('Location: '.$url.'add_users_to_session.php?id_session='.$sessionId.'&add=true');
} else {
header('Location: '.$url.'resume_session.php?id_session='.$sessionId);
}
exit;
}
Display::display_header($tool_name);
if ('multiple' === $add_type) {
$link_add_type_unique = '<a href="'.api_get_self().'?id_session='.$sessionId.'&add='.$add.'&add_type=unique">'.
Display::return_icon('single.gif').get_lang('Single registration').'</a>';
$link_add_type_multiple = Display::url(Display::return_icon('multiple.gif').get_lang('Multiple registration'), '#');
} else {
$link_add_type_unique = Display::url(Display::return_icon('single.gif').get_lang('Single registration'), '#');
$link_add_type_multiple = '<a href="'.api_get_self().'?id_session='.$sessionId.'&add='.$add.'&add_type=multiple">'.
Display::return_icon('multiple.gif').get_lang('Multiple registration').'</a>';
}
// the form header
$session_info = SessionManager::fetch($sessionId);
echo Display::toolbarAction('toolbar', [$link_add_type_unique.$link_add_type_multiple]);
$ajax_search = 'unique' === $add_type ? true : false;
$nosessionCourses = $sessionCourses = [];
if ($ajax_search) {
$sql = "SELECT course.id, code, title, visual_code, session_id
FROM $tbl_course course
INNER JOIN $tbl_session_rel_course session_rel_course
ON
course.id = session_rel_course.c_id AND
session_rel_course.session_id = $sessionId
ORDER BY ".(count($courses) ? "(code IN (".implode(',', $courses).")) DESC," : '')." title";
if (api_is_multiple_url_enabled()) {
$tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
$access_url_id = api_get_current_access_url_id();
if (-1 != $access_url_id) {
$sql = "SELECT course.id, code, title, visual_code, session_id
FROM $tbl_course course
INNER JOIN $tbl_session_rel_course session_rel_course
ON course.id = session_rel_course.c_id AND session_rel_course.session_id = $sessionId
INNER JOIN $tbl_course_rel_access_url url_course
ON (url_course.c_id = course.id)
WHERE access_url_id = $access_url_id
ORDER BY ".(count($courses) ? " (code IN(".implode(',', $courses).")) DESC," : '')." title";
}
}
$result = Database::query($sql);
$Courses = Database::store_result($result);
foreach ($Courses as $course) {
$sessionCourses[$course['id']] = $course;
}
} else {
$sql = "SELECT course.id, code, title, visual_code, session_id
FROM $tbl_course course
LEFT JOIN $tbl_session_rel_course session_rel_course
ON
course.id = session_rel_course.c_id AND
session_rel_course.session_id = $sessionId
ORDER BY ".(count($courses) ? "(code IN(".implode(',', $courses).")) DESC," : '')." title";
if (api_is_multiple_url_enabled()) {
$tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
$access_url_id = api_get_current_access_url_id();
if (-1 != $access_url_id) {
$sql = "SELECT course.id, code, title, visual_code, session_id
FROM $tbl_course course
LEFT JOIN $tbl_session_rel_course session_rel_course
ON
course.id = session_rel_course.c_id AND
session_rel_course.session_id = $sessionId
INNER JOIN $tbl_course_rel_access_url url_course
ON (url_course.c_id = course.id)
WHERE access_url_id = $access_url_id
ORDER BY ".(count($courses) ? "(code IN(".implode(',', $courses).")) DESC," : '')." title";
}
}
$result = Database::query($sql);
$Courses = Database::store_result($result);
foreach ($Courses as $course) {
if ($course['session_id'] == $sessionId) {
$sessionCourses[$course['id']] = $course;
} else {
$nosessionCourses[$course['id']] = $course;
}
}
}
if (!api_is_platform_admin() && api_is_teacher()) {
$coursesFromTeacher = CourseManager::getCoursesFollowedByUser(
api_get_user_id(),
COURSEMANAGER
);
foreach ($nosessionCourses as &$course) {
if (in_array($course['code'], array_keys($coursesFromTeacher))) {
continue;
} else {
unset($nosessionCourses[$course['id']]);
}
}
}
unset($Courses);
echo Display::page_header($tool_name.' ('.$session_info['name'].')');
?>
<form name="formulaire"
method="post"
action="<?php echo api_get_self(); ?>?page=<?php echo $page; ?>&id_session=<?php echo $sessionId;
if (!empty($_GET['add'])) {
echo '&add=true';
} ?>" style="margin:0px;" <?php if ($ajax_search) {
echo ' onsubmit="valide();"';
} ?>>
<input type="hidden" name="formSent" value="1"/>
<div id="multiple-add-session" class="grid grid-cols-3">
<div class="col-md-4">
<label><?php echo get_lang('Courses list'); ?> :</label>
<?php
if (!('multiple' === $add_type)) {
?>
<input type="text" id="course_to_add"
onkeyup="xajax_search_courses(this.value, 'single', <?php echo $sessionId; ?>)"
class="w-full"/>
<div id="ajax_list_courses_single"></div>
<?php
} else {
?>
<div id="ajax_list_courses_multiple">
<select id="origin" name="NoSessionCoursesList[]"
multiple="multiple" size="20"
class="w-full">
<?php foreach ($nosessionCourses as $enreg) {
?>
<option value="<?php echo $enreg['id']; ?>" <?php echo 'title="'.htmlspecialchars(
$enreg['title'].' ('.$enreg['visual_code'].')',
ENT_QUOTES
).'"';
if (in_array($enreg['code'], $CourseList)) {
echo 'selected="selected"';
} ?>>
<?php echo $enreg['title'].' ('.$enreg['visual_code'].')'; ?>
</option>
<?php
} ?>
</select>
</div>
<?php
}
unset($nosessionCourses);
?>
</div>
<div class="col-md-4">
<?php if ('multiple' == $add_type) {
?>
<div class="code-course">
<?php echo get_lang('First letter (code)'); ?> :
<select name="firstLetterCourse"
onchange="xajax_search_courses(this.value,'multiple', <?php echo $sessionId; ?>)"
class="selectpicker form-control">
<option value="%">--</option>
<?php
echo Display:: get_alphabet_options();
echo Display:: get_numeric_options(0, 9, ''); ?>
</select>
</div>
<?php
} ?>
<div class="control-course">
<?php
if ($ajax_search) {
?>
<div class="separate-action">
<button class="btn btn-primary" type="button"
onclick="remove_item(document.getElementById('destination'))">
<em class="fa fa-chevron-left"></em>
</button>
</div>
<?php
} else {
?>
<div class="separate-action">
<button name="add_course" class="btn btn-primary" type="button"
onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))"
onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))">
<em class="fa fa-chevron-right"></em>
</button>
</div>
<div class="separate-action">
<button name="remove_course" class="btn btn-primary" type="button"
onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))"
onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))">
<em class="fa fa-chevron-left"></em>
</button>
</div>
<?php
} ?>
<div class="separate-action">
<label>
<input type="checkbox" name="copy_evaluation">
<?php echo get_lang('Import gradebook from base course'); ?>
</label>
<label>
<input type="checkbox" name="import_teachers_as_course_coach">
<?php echo get_lang('Import course teachers as course coach in the session'); ?>
</label>
</div>
<?php
echo '<div class="separate-action">';
if (isset($_GET['add'])) {
echo '<button name="next" class="btn btn-success" type="button" value="" onclick="valide()" >'.get_lang(
'Next step'
).'</button>';
} else {
echo '<button name="next" class="btn btn-success" type="button" value="" onclick="valide()" >'.get_lang(
'Add courses to this session'
).'</button>';
}
echo '</div>';
?>
</div>
</div>
<div class="col-md-4">
<label><?php echo get_lang('Courses in this session'); ?> :</label>
<select id='destination' name="SessionCoursesList[]" multiple="multiple" size="20" class="w-full">
<?php
foreach ($sessionCourses as $enreg) {
?>
<option value="<?php echo $enreg['id']; ?>" title="<?php echo htmlspecialchars(
$enreg['title'].' ('.$enreg['visual_code'].')',
ENT_QUOTES
); ?>">
<?php echo $enreg['title'].' ('.$enreg['visual_code'].')'; ?>
</option>
<?php
}
unset($sessionCourses);
?>
</select>
</div>
</div>
</form>
<script>
function moveItem(origin, destination) {
for (var i = 0; i < origin.options.length; i++) {
if (origin.options[i].selected) {
destination.options[destination.length] = new Option(origin.options[i].text, origin.options[i].value);
origin.options[i] = null;
i = i - 1;
}
}
destination.selectedIndex = -1;
sortOptions(destination.options);
}
function sortOptions(options) {
newOptions = new Array();
for (i = 0; i < options.length; i++) {
newOptions[i] = options[i];
}
newOptions = newOptions.sort(mysort);
options.length = 0;
for (i = 0; i < newOptions.length; i++) {
options[i] = newOptions[i];
}
}
function mysort(a, b) {
if (a.text.toLowerCase() > b.text.toLowerCase()) {
return 1;
}
if (a.text.toLowerCase() < b.text.toLowerCase()) {
return -1;
}
return 0;
}
function valide() {
var options = document.getElementById('destination').options;
for (i = 0; i < options.length; i++)
options[i].selected = true;
document.forms.formulaire.submit();
}
</script>
<?php
echo Display::page_header($tool_name.' ('.$session->getName().')');
echo $contentForm;
Display::display_footer();

@ -9,7 +9,6 @@ require_once __DIR__.'/../inc/global.inc.php';
$xajax = new xajax();
$xajax->registerFunction('search_users');
// setting the section (for the tabs)
$this_section = SECTION_PLATFORM_ADMIN;
$id_session = isset($_GET['id_session']) ? (int) $_GET['id_session'] : 0;

@ -127,7 +127,7 @@ if ($isMultipleUrl) {
}
$url = Display::url(
Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL),
Display::return_icon('add.png', get_lang('Add'), [], ICON_SIZE_SMALL),
"add_courses_to_session.php?page=resume_session.php&id_session=$sessionId"
);
$courseListToShow = Display::page_subheader(get_lang('Course list').$url);
@ -268,7 +268,7 @@ if (0 === $session->getNbrCourses()) {
$courseListToShow .= '</table><br />';
$url = '&nbsp;'.Display::url(
Display::return_icon('user_subscribe_session.png', get_lang('Add')),
Display::return_icon('add.png', get_lang('Add')),
$codePath."session/add_users_to_session.php?page=resume_session.php&id_session=$sessionId"
);
$url .= Display::url(

@ -166,3 +166,4 @@ $form->setDefaults(['id_coach' => $selected]);
$form->display();
Display::display_footer();

@ -11,14 +11,11 @@ Feature: Session access
And I fill in select2 input "#coach_username" with id "1" and value "admin"
And I press "submit"
Then I should see "Add courses to this session (Session1)"
Then I select "TEMP_PRIVATE (TEMPPRIVATE)" from "NoSessionCoursesList[]"
And I press "add_course"
And I press "next"
Then I fill in select2 input "#courses" with id "1" and value "TEMPPRIVATE"
And I press "submit"
And wait very long for the page to be loaded
Then I should see "Update successful"
Then I should see "Subscribe users to this session"
Then I follow "Multiple registration"
And wait the page to be loaded when ready
Then I select "Apple Maggart Fiona (fapple)" from "nosessionUsersList[]"
And I press "add_user"
And I press "next"

Loading…
Cancel
Save