Internal: Update from 1.11.x

pull/3544/head
Julio Montoya 5 years ago
parent 87512579f6
commit fdc597a1fd
  1. 7
      public/main/mySpace/access_details.php
  2. 6
      public/main/mySpace/access_details_session.php
  3. 8
      public/main/mySpace/admin.php
  4. 77
      public/main/mySpace/admin_view.php
  5. 9
      public/main/mySpace/course.php
  6. 2
      public/main/mySpace/current_courses.php
  7. 10
      public/main/mySpace/progression.php
  8. 276
      public/main/mySpace/session.php
  9. 206
      public/main/mySpace/session_filter.php
  10. 20
      public/main/mySpace/student.php
  11. 1
      public/main/mySpace/teachers.php
  12. 2
      public/main/survey/edit_meeting.php
  13. 22
      public/main/survey/fillsurvey.php
  14. 86
      public/main/survey/reporting.php
  15. 6
      public/main/survey/survey.download.inc.php
  16. 62
      public/main/survey/survey.lib.php
  17. 145
      public/main/survey/surveyUtil.class.php
  18. 2
      public/main/survey/survey_invitation.php
  19. 282
      public/main/survey/survey_list.php
  20. 4
      public/main/survey/survey_question.php

@ -16,10 +16,10 @@ require_once __DIR__.'/../inc/global.inc.php';
api_block_anonymous_users();
// Access restrictions.
$is_allowedToTrack = api_is_platform_admin(true, true) ||
$allowToTrack = api_is_platform_admin(true, true) ||
api_is_teacher() || api_is_course_tutor();
if (!$is_allowedToTrack) {
if (!$allowToTrack) {
api_not_allowed(true);
exit;
}
@ -138,7 +138,8 @@ $userInfo = api_get_user_info($user_id);
echo Display::page_header(get_lang('Learner details in course'));
echo Display::page_subheader(
get_lang('User').': '.$userInfo['complete_name'].' - '.get_lang('Course').': '.$courseInfo['title'].' ('.$course_code.')'
get_lang('User').': '.$userInfo['complete_name'].' - '.
get_lang('Course').': '.$courseInfo['title'].' ('.$course_code.')'
);
$form->setDefaults(['from' => $from, 'to' => $to]);

@ -244,7 +244,7 @@ function getReport($userId, $from, $to, $addTime = false)
}
}
$table = new HTML_Table(['class' => 'data_table']);
$table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
$headers = [
get_lang('First connection'),
get_lang('Last connection'),
@ -276,7 +276,7 @@ function getReport($userId, $from, $to, $addTime = false)
$courseSessionTable .= '<div class="data-title">'.Display::page_subheader3(
$iconCourse.$data['name'][$courseId]
).'</div>';
$table = new HTML_Table(['class' => 'data_table']);
$table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
$headers = [
get_lang('Start Date'),
get_lang('End Date'),
@ -306,7 +306,7 @@ function getReport($userId, $from, $to, $addTime = false)
}
$totalCourseSessionTable = '';
if ($courseSessionTableData) {
$table = new HTML_Table(['class' => 'data_table']);
$table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
$headers = [
get_lang('Course'),
get_lang('TotalDuration'),

@ -38,9 +38,13 @@ $sql = "SELECT user.id as user_id,lastname,firstname,email
$result_admins = Database::query($sql);
if (api_is_western_name_order()) {
echo '<table class="data_table"><tr><th>'.get_lang('First name').'</th><th>'.get_lang('Last name').'</th><th>'.get_lang('e-mail').'</th></tr>';
echo '<table class="table table-hover table-striped data_table">
<tr><th>'.get_lang('First name').'</th>
<th>'.get_lang('Last name').'</th><th>'.get_lang('e-mail').'</th></tr>';
} else {
echo '<table class="data_table"><tr><th>'.get_lang('Last name').'</th><th>'.get_lang('First name').'</th><th>'.get_lang('e-mail').'</th></tr>';
echo '<table class="table table-hover table-striped data_table">
<tr><th>'.get_lang('Last name').'</th>
<th>'.get_lang('First name').'</th><th>'.get_lang('e-mail').'</th></tr>';
}
if (api_is_western_name_order(PERSON_NAME_DATA_EXPORT)) {

@ -8,10 +8,47 @@ require_once __DIR__.'/../inc/global.inc.php';
api_block_anonymous_users();
$exportCSV = isset($_GET['export']) && 'csv' === $_GET['export'] ? true : false;
$exportCSV = isset($_GET['export']) && $_GET['export'] === 'csv' ? true : false;
if (isset($_GET['export_csv']) && $exportCSV == false) {
// to export learningPath and company
$exportCSV = true;
}
$startDate = isset($_GET['startDate']) ? $_GET['startDate'] : null;
$endDate = isset($_GET['endDate']) ? $_GET['endDate'] : null;
$display = isset($_GET['display']) ? Security::remove_XSS($_GET['display']) : null;
if (isset($_POST['display']) && $display == null) {
$display = Security::remove_XSS($_POST['display']);
}
$htmlHeadXtra[] = api_get_jqgrid_js();
$htmlHeadXtra[] = '<script
type="text/javascript"
src="'.api_get_path(WEB_PUBLIC_PATH).'assets/jquery.easy-pie-chart/dist/jquery.easypiechart.js"></script>
<script type="text/javascript">
// show hide a student based on BT#17648
function showHideStudent(el){
if($("#"+el).hasClass("hidden")){
$("#"+el).removeClass("hidden");
$("#"+el+"_").find(".icon_add").addClass("hidden");
$("#"+el+"_").find(".icon_remove").removeClass("hidden");
}else{
$("#"+el).addClass("hidden")
$("#"+el+"_").find(".icon_add").removeClass("hidden");
$("#"+el+"_").find(".icon_remove").addClass("hidden");
}
}
function ShowMoreAuthor(el){
if($(".author_"+el).hasClass("hidden")){
$(".author_"+el).removeClass("hidden");
$(".icon_remove_author_"+el).removeClass("hidden");
$(".icon_add_author_"+el).addClass("hidden");
}else{
$(".author_"+el).addClass("hidden")
$(".icon_remove_author_"+el).addClass("hidden");
$(".icon_add_author_"+el).removeClass("hidden");
}
}
</script>';
// the section (for the tabs)
$this_section = SECTION_TRACKING;
@ -33,6 +70,15 @@ if ($exportCSV) {
} elseif ('course' === $display) {
MySpace::export_tracking_course_overview();
exit;
} elseif ('company' === $display) {
MySpace::exportCompanyResumeCsv($startDate, $endDate);
exit;
} elseif ('learningPath' === $display) {
MySpace::displayResumeLP($startDate, $endDate, true);
exit;
} elseif ('learningPathByItem' === $display) {
MySpace::displayResumeLpByItem($startDate, $endDate, true);
exit;
}
}
@ -55,12 +101,39 @@ switch ($display) {
case 'course':
MySpace::display_tracking_course_overview();
break;
case 'company':
MySpace::displayResumeCompany($startDate, $endDate);
break;
case 'learningPath':
MySpace::displayResumeLP($startDate, $endDate);
break;
case 'learningPathByItem':
MySpace::displayResumeLpByItem($startDate, $endDate);
break;
case 'accessoverview':
$courseId = isset($_GET['course_id']) ? (int) $_GET['course_id'] : 0;
if ($courseId == 0 && $_POST['course_id']) {
$courseId = (int) $_POST['course_id'];
$_GET['course_id'] = $courseId;
}
$sessionId = isset($_GET['session_id']) ? (int) $_GET['session_id'] : 0;
if ($sessionId == 0 && $_POST['session_id']) {
$sessionId = (int) $_POST['session_id'];
$_GET['session_id'] = $sessionId;
}
$studentId = isset($_GET['student_id']) ? (int) $_GET['student_id'] : 0;
if ($studentId == 0 && $_POST['student_id']) {
$studentId = (int) $_POST['student_id'];
$_GET['student_id'] = $studentId;
}
$perPage = isset($_GET['tracking_access_overview_per_page']) ? $_GET['tracking_access_overview_per_page'] : 20;
MySpace::displayTrackingAccessOverView($courseId, $sessionId, $studentId);
$dates = isset($_GET['date']) ? $_GET['date'] : null;
if ($dates == null && $_POST['date']) {
$dates = $_POST['date'];
$_GET['date'] = $dates;
}
MySpace::displayTrackingAccessOverView($courseId, $sessionId, $studentId, $perPage, $dates);
break;
}

@ -104,6 +104,15 @@ if (api_is_platform_admin(true, true)) {
Display::return_icon('session.png', get_lang('Course sessions'), [], ICON_SIZE_MEDIUM),
'session.php'
);
$menu_items[] = Display::url(
get_lang('QuestionStats'),
api_get_path(WEB_CODE_PATH).'mySpace/question_stats_global.php'
);
$menu_items[] = Display::url(
get_lang('QuestionStatsDetailedReport'),
api_get_path(WEB_CODE_PATH).'mySpace/question_stats_global_detail.php'
);
if (api_can_login_as($user_id)) {
$link = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.Security::get_existing_token().'">'.
Display::return_icon('login_as.png', get_lang('Login as'), null, ICON_SIZE_MEDIUM).'</a>&nbsp;&nbsp;';

@ -221,7 +221,7 @@ if (isset($_GET['export'])) {
$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('Reporting')];
Display::display_header(get_lang('Current courses'));
$table = new HTML_Table(['class' => 'data_table']);
$table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
$row = 0;
$column = 0;
foreach ($headers as $header) {

@ -39,8 +39,14 @@ if (Database::num_rows($result_course) > 0) {
$export_result = export_csv($header, $data, 'test.csv'); // TODO: There is no data for exporting yet.
echo Display::return_message($export_result, 'error');
}
echo '<table class="data_table"><tr><th>'.get_lang('Course').'</th><th>'.get_lang('Frequentation time').'</th><th>'.get_lang('Progress').'</th><th>'.get_lang('Tests score').'</th></tr>';
$header = [get_lang('Course'), get_lang('Frequentation time'), get_lang('Progress'), get_lang('Tests score')];
echo '<table class="table table-hover table-striped data_table">
<tr>
<th>'.get_lang('Course').'</th>
<th>'.get_lang('TempsFrequentation').'</th>
<th>'.get_lang('Progression').'</th>
<th>'.get_lang('MoyenneTest').'</th>
</tr>';
$header = [get_lang('Course'), get_lang('TempsFrequentation'), get_lang('Progression'), get_lang('MoyenneTest')];
while ($a_course = Database::fetch_array($result_course)) {
// TODO: This query is to be checked, there are no HotPotatoes tests results.
$sql_moy_test = "SELECT score,max_score

@ -12,6 +12,7 @@ $export_csv = false;
if (isset($_REQUEST['export']) && 'csv' == $_REQUEST['export']) {
$export_csv = true;
}
$action = isset($_GET['action']) ? $_GET['action'] : '';
$id_coach = api_get_user_id();
if (isset($_REQUEST['id_coach']) && '' != $_REQUEST['id_coach']) {
@ -24,6 +25,277 @@ if (!$allowToTrack) {
api_not_allowed(true);
}
$studentId = isset($_GET['student']) ? (int) $_GET['student'] : 0;
$sessionId = isset($_GET['sid']) ? (int) $_GET['sid'] : 0;
$currentUrl = api_get_self().'?student='.$studentId.'&sid='.$sessionId;
switch ($action) {
case 'export_to_pdf':
$allStudents = isset($_GET['all_students']) && 1 === (int) $_GET['all_students'] ? true : false;
$sessionToExport = isset($_GET['session_to_export']) ? (int) $_GET['session_to_export'] : 0;
$type = isset($_GET['type']) ? $_GET['type'] : 'attendance';
$sessionInfo = api_get_session_info($sessionToExport);
if (empty($sessionInfo)) {
api_not_allowed(true);
}
$courses = Tracking::get_courses_list_from_session($sessionToExport);
$studentList = [$studentId];
if ($allStudents) {
$users = SessionManager::get_users_by_session($sessionToExport, 0);
$studentList = array_column($users, 'user_id');
}
$totalCourses = count($courses);
$scoreDisplay = ScoreDisplay::instance();
$table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
$pdfList = [];
foreach ($studentList as $studentId) {
$studentInfo = api_get_user_info($studentId);
$timeSpent = 0;
$numberVisits = 0;
$progress = 0;
$timeSpentPerCourse = [];
$progressPerCourse = [];
foreach ($courses as $course) {
$courseId = $course['c_id'];
$courseTimeSpent = Tracking::get_time_spent_on_the_course($studentId, $courseId, $sessionToExport);
$timeSpentPerCourse[$courseId] = $courseTimeSpent;
$timeSpent += $courseTimeSpent;
$sql = "SELECT DISTINCT count(course_access_id) as count
FROM $table
WHERE
c_id = $courseId AND
session_id = $sessionToExport AND
user_id = $studentId";
$result = Database::query($sql);
$row = Database::fetch_array($result);
$numberVisits += $row['count'];
$courseProgress = Tracking::get_avg_student_progress(
$studentId,
$course['code'],
[],
$sessionToExport
);
$progressPerCourse[$courseId] = $courseProgress;
$progress += $courseProgress;
}
$average = round($progress / $totalCourses, 1);
$average = empty($average) ? '0%' : $average.'%';
$first = Tracking::get_first_connection_date($studentId);
$last = Tracking::get_last_connection_date($studentId);
$timeSpentContent = '';
$pdfTitle = get_lang('AttestationOfAttendance');
if ('attendance' === $type) {
$table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
$column = 0;
$row = 0;
$headers = [
get_lang('TimeSpent'),
get_lang('NumberOfVisits'),
get_lang('GlobalProgress'),
get_lang('FirstLogin'),
get_lang('LastConnexionDate'),
];
foreach ($headers as $header) {
$table->setHeaderContents($row, $column, $header);
$column++;
}
$table->setCellContents(1, 0, api_time_to_hms($timeSpent));
$table->setCellContents(1, 1, $numberVisits);
$table->setCellContents(1, 2, $average);
$table->setCellContents(1, 3, $first);
$table->setCellContents(1, 4, $last);
$timeSpentContent = $table->toHtml();
} else {
$pdfTitle = get_lang('CertificateOfAchievement');
}
$courseTable = '';
if (!empty($courses)) {
$courseTable .= '<table class="table table-hover table-striped data_table">';
$courseTable .= '<thead>';
$courseTable .= '<tr>
<th>'.get_lang('FormationUnit').'</th>
<th>'.get_lang('ConnectionTime').'</th>
<th>'.get_lang('Progress').'</th>';
if ('attendance' === $type) {
$courseTable .= '<th>'.get_lang('Score').'</th>';
}
$courseTable .= '</tr>';
$courseTable .= '</thead>';
$courseTable .= '<tbody>';
$totalCourseTime = 0;
$totalAttendance = [0, 0];
$totalScore = 0;
$totalProgress = 0;
$gradeBookTotal = [0, 0];
$totalEvaluations = '0/0 (0%)';
foreach ($courses as $course) {
$courseId = $course['c_id'];
$courseInfoItem = api_get_course_info_by_id($courseId);
$courseId = $courseInfoItem['real_id'];
$courseCodeItem = $courseInfoItem['code'];
$isSubscribed = CourseManager::is_user_subscribed_in_course(
$studentId,
$courseCodeItem,
true,
$sessionToExport
);
if ($isSubscribed) {
$timeInSeconds = $timeSpentPerCourse[$courseId];
$totalCourseTime += $timeInSeconds;
$time_spent_on_course = api_time_to_hms($timeInSeconds);
$progress = $progressPerCourse[$courseId];
$totalProgress += $progress;
$bestScore = Tracking::get_avg_student_score(
$studentId,
$courseCodeItem,
[],
$sessionToExport,
false,
false,
true
);
if (is_numeric($bestScore)) {
$totalScore += $bestScore;
}
$progress = empty($progress) ? '0%' : $progress.'%';
$score = empty($bestScore) ? '0%' : $bestScore.'%';
$courseTable .= '<tr>
<td>
<a href="'.$courseInfoItem['course_public_url'].'?id_session='.$sessionToExport.'">'.
$courseInfoItem['title'].'</a>
</td>
<td >'.$time_spent_on_course.'</td>
<td >'.$progress.'</td>';
if ('attendance' === $type) {
$courseTable .= '<td >'.$score.'</td>';
}
$courseTable .= '</tr>';
}
}
$totalAttendanceFormatted = $scoreDisplay->display_score($totalAttendance);
$totalScoreFormatted = $scoreDisplay->display_score([$totalScore / $totalCourses, 100], SCORE_AVERAGE);
$totalProgressFormatted = $scoreDisplay->display_score(
[$totalProgress / $totalCourses, 100],
SCORE_AVERAGE
);
$totalEvaluations = $scoreDisplay->display_score($gradeBookTotal);
$totalTimeFormatted = api_time_to_hms($totalCourseTime);
$courseTable .= '
<tr>
<th>'.get_lang('Total').'</th>
<th>'.$totalTimeFormatted.'</th>
<th>'.$totalProgressFormatted.'</th>
';
if ('attendance' === $type) {
$courseTable .= '<th>'.$totalScoreFormatted.'</th>';
}
$courseTable .= '</tr>';
$courseTable .= '</tbody></table>';
}
$tpl = new Template('', false, false, false, true, false, false);
$tpl->assign('title', $pdfTitle);
$tpl->assign('session_title', $sessionInfo['name']);
$tpl->assign('session_info', $sessionInfo);
$sessionCategoryTitle = '';
if (isset($sessionInfo['session_category_id'])) {
$sessionCategory = SessionManager::get_session_category($sessionInfo['session_category_id']);
if ($sessionCategory) {
$sessionCategoryTitle = $sessionCategory['name'];
}
}
$dateData = SessionManager::parseSessionDates($sessionInfo, false);
$dateToString = $dateData['access'];
$tpl->assign('session_display_dates', $dateToString);
$tpl->assign('session_category_title', $sessionCategoryTitle);
$tpl->assign('student', $studentInfo['complete_name']);
$tpl->assign('student_info', $studentInfo);
$tpl->assign('student_info_extra_fields', UserManager::get_extra_user_data($studentInfo['user_id']));
$tpl->assign('table_progress', $timeSpentContent);
$tpl->assign(
'subtitle',
sprintf(
get_lang('InSessionXYouHadTheFollowingResults'),
$sessionInfo['name']
)
);
$tpl->assign('table_course', $courseTable);
$template = 'pdf_export_student.tpl';
if ('achievement' === $type) {
$template = 'certificate_achievement.tpl';
}
$content = $tpl->fetch($tpl->get_template('my_space/'.$template));
$params = [
'pdf_title' => get_lang('Resume'),
'session_info' => $sessionInfo,
'course_info' => '',
'pdf_date' => '',
'student_info' => $studentInfo,
'show_grade_generated_date' => true,
'show_real_course_teachers' => false,
'show_teacher_as_myself' => false,
'orientation' => 'P',
];
@$pdf = new PDF('A4', $params['orientation'], $params);
$pdf->setBackground($tpl->theme);
$mode = 'D';
$pdfName = $sessionInfo['name'].'_'.$studentInfo['complete_name'];
if ($allStudents) {
$mode = 'F';
$pdfName = $studentInfo['complete_name'];
}
$pdf->set_footer();
$result = @$pdf->content_to_pdf(
$content,
'',
$pdfName,
null,
$mode,
false,
null,
false,
true,
false
);
$pdfList[] = $result;
}
if (empty($pdfList)) {
api_not_allowed(true);
}
// Creating a ZIP file.
$tempZipFile = api_get_path(SYS_ARCHIVE_PATH).uniqid('report_session_'.$sessionToExport, true).'.zip';
$zip = new PclZip($tempZipFile);
foreach ($pdfList as $file) {
$zip->add(
$file,
PCLZIP_OPT_REMOVE_PATH,
api_get_path(SYS_ARCHIVE_PATH)
);
}
$name = $sessionInfo['name'].'_'.api_get_utc_datetime().'.zip';
DocumentManager::file_send_for_download($tempZipFile, true, $name);
exit;
break;
}
$htmlHeadXtra[] = api_get_jqgrid_js();
$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('Reporting')];
Display::display_header(get_lang('Course sessions'));
@ -210,7 +482,7 @@ $orderUrl = api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=order';
// Cleaning
for (key in added_cols) {
grid.hideCol(key);
};
}
grid.showCol('name');
grid.showCol('display_start_date');
grid.showCol('display_end_date');
@ -221,7 +493,7 @@ $orderUrl = api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=order';
grid.showCol('name').trigger('reloadGrid');
for (key in added_cols) {
grid.showCol(key);
};
}
}
var second_filters = [];

@ -27,14 +27,73 @@ define('DATE_END_FILTER', 2);
define('ALL_DATE_FILTER', 3);
$certificateList = [];
$formSent = 0;
$urlParam = '';
$form = new FormValidator('search_user', 'GET', api_get_self());
$innerJoinSessionRelUser = '';
$whereCondictionDRH = '';
$whereCondictionMultiUrl = '';
if (api_is_drh()) {
$innerJoinSessionRelUser = "INNER JOIN $tblSessionRelUser as session_rel_user
ON (s.id = session_rel_user.session_id)";
$whereCondictionDRH = "WHERE session_rel_user.user_id = ".api_get_user_id();
$whereCondictionMultiUrl = " AND session_rel_user.user_id = ".api_get_user_id();
}
$sql = "SELECT s.id, name FROM $tblSession s
$innerJoinSessionRelUser
$whereCondictionDRH
ORDER BY name";
if (api_is_multiple_url_enabled()) {
$tblSessionRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
$accessUrlId = api_get_current_access_url_id();
if ($accessUrlId != -1) {
$sql = "SELECT s.id, name FROM $tblSession s
INNER JOIN $tblSessionRelAccessUrl as session_rel_url
ON (s.id = session_rel_url.session_id)
$innerJoinSessionRelUser
WHERE access_url_id = $accessUrlId
$whereCondictionMultiUrl
ORDER BY name";
}
}
$result = Database::query($sql);
$Sessions = Database::store_result($result);
$options = [];
$options['0'] = '';
foreach ($Sessions as $enreg) {
$options[$enreg['id']] = $enreg['name'];
}
if (isset($_POST['formSent'])) {
$formSent = $_POST['formSent'];
$sessionId = (int) $_POST['session_id'];
$dateBegin = isset($_POST['date_begin']) ? strtotime($_POST['date_begin']) : null;
$dateEnd = isset($_POST['date_end']) ? strtotime($_POST['date_end'].' 23:59:59') : null;
$form->addElement('select', 'session_id', get_lang('SessionList'), $options, ['id' => 'session-id']);
$form->addDatePicker('date_begin', get_lang('DateStart'), ['id' => 'date-begin']);
$form->addDatePicker('date_end', get_lang('DateEnd'), ['id' => 'date-end']);
// EXTRA FIELDS
$extraField = new ExtraField('user');
$returnParams = $extraField->addElements(
$form,
0,
[],
true,
false,
[],
[],
[],
false,
true
);
$form->addElement('hidden', 'formSent', 1);
$form->addButtonSearch(get_lang('Search'));
$form->addButtonExport(get_lang('ExportAsCSV'), 'export');
if ($form->validate()) {
$values = $form->getSubmitValues();
$exportToCsv = isset($values['export']);
$sessionId = (int) $_REQUEST['session_id'];
$dateBegin = isset($_REQUEST['date_begin']) ? strtotime($_REQUEST['date_begin']) : null;
$dateEnd = isset($_REQUEST['date_end']) ? strtotime($_REQUEST['date_end'].' 23:59:59') : null;
$filterDate = 0;
if (!empty($dateBegin)) {
@ -48,7 +107,7 @@ if (isset($_POST['formSent'])) {
$extraField = new ExtraField('user');
$extraFieldsAll = $extraField->get_all(['filter = ?' => 1], 'option_order');
foreach ($extraFieldsAll as $field) {
if (!empty($_POST['extra_'.$field['variable']])) {
if (!empty($_REQUEST['extra_'.$field['variable']])) {
$filterCheckList[$field['id']] = $field;
}
}
@ -137,19 +196,19 @@ if (isset($_POST['formSent'])) {
switch ($field['field_type']) {
case ExtraField::FIELD_TYPE_TEXT:
case ExtraField::FIELD_TYPE_ALPHANUMERIC:
$pos = stripos($extraFieldValueData['value'], $_POST['extra_'.$field['variable']]);
if (false === $pos) {
$pos = stripos($extraFieldValueData['value'], $_REQUEST['extra_'.$field['variable']]);
if ($pos === false) {
unset($certificateList[$key]);
}
break;
case ExtraField::FIELD_TYPE_RADIO:
$valueRadio = $_POST['extra_'.$field['variable']]['extra_'.$field['variable']];
$valueRadio = $_REQUEST['extra_'.$field['variable']]['extra_'.$field['variable']];
if ($extraFieldValueData['value'] != $valueRadio) {
unset($certificateList[$key]);
}
break;
case ExtraField::FIELD_TYPE_SELECT:
if ($extraFieldValueData['value'] != $_POST['extra_'.$field['variable']]) {
if ($extraFieldValueData['value'] != $_REQUEST['extra_'.$field['variable']]) {
unset($certificateList[$key]);
}
break;
@ -159,15 +218,69 @@ if (isset($_POST['formSent'])) {
}
$params = [
'session_id' => (int) $_POST['session_id'],
'date_begin' => Security::remove_XSS($_POST['date_begin']),
'date_end' => Security::remove_XSS($_POST['date_end']),
'session_id' => (int) $_REQUEST['session_id'],
'date_begin' => Security::remove_XSS($_REQUEST['date_begin']),
'date_end' => Security::remove_XSS($_REQUEST['date_end']),
];
//select of sessions
foreach ($filterCheckList as $field) {
$params['extra_'.$field['variable']] = Security::remove_XSS($_POST['extra_'.$field['variable']]);
$params['extra_'.$field['variable']] = Security::remove_XSS($_REQUEST['extra_'.$field['variable']]);
}
$urlParam = http_build_query($params);
$dataToExport = [];
if ($exportToCsv) {
$headers = [
get_lang('Session'),
get_lang('Course'),
get_lang('FirstName'),
get_lang('LastName'),
get_lang('Score'),
get_lang('Date'),
];
$extraField = new ExtraField('user');
foreach ($extraFieldsAll as $field) {
$headers[] = $field['display_text'];
}
$dataToExport[] = $headers;
$sessionInfo = api_get_session_info($sessionId);
foreach ($certificateList as $index => $value) {
$categoryId = $value['category_id'];
$courseCode = $value['course_code'];
$courseInfo = api_get_course_info($courseCode);
$extraFields = [];
foreach ($extraFieldsAll as $field) {
$extraFieldValue = new ExtraFieldValue('user');
$extraFieldValueData = $extraFieldValue->get_values_by_handler_and_field_id(
$value['user_id'],
$field['id']
);
$fieldValue = isset($extraFieldValueData['value']) ? $extraFieldValueData['value'] : '';
if ('true' === $fieldValue) {
$fieldValue = get_lang('Yes');
}
if ('false' === $fieldValue) {
$fieldValue = get_lang('No');
}
$extraFields[] = $fieldValue;
}
$list = GradebookUtils::get_list_gradebook_certificates_by_user_id($value['user_id'], $categoryId);
foreach ($list as $valueCertificate) {
$item = [];
$item[] = $sessionInfo['name'];
$item[] = $courseInfo['title'];
$item[] = $value['firstname'];
$item[] = $value['lastname'];
$item[] = $valueCertificate['score_certificate'];
$item[] = api_get_local_time($valueCertificate['created_at']);
$item = array_merge($item, $extraFields);
$dataToExport[] = $item;
}
}
Export::arrayToCsv($dataToExport, 'export');
}
}
$htmlHeadXtra[] = "<script>
@ -209,65 +322,6 @@ $htmlHeadXtra[] = "<script>
});
</script>";
$innerJoinSessionRelUser = '';
$whereCondictionDRH = '';
$whereCondictionMultiUrl = '';
if (api_is_drh()) {
$innerJoinSessionRelUser = "INNER JOIN $tblSessionRelUser as session_rel_user
ON (s.id = session_rel_user.session_id)";
$whereCondictionDRH = "WHERE session_rel_user.user_id = ".api_get_user_id();
$whereCondictionMultiUrl = " AND session_rel_user.user_id = ".api_get_user_id();
}
//select of sessions
$sql = "SELECT s.id, name FROM $tblSession s
$innerJoinSessionRelUser
$whereCondictionDRH
ORDER BY name";
if (api_is_multiple_url_enabled()) {
$tblSessionRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
$accessUrlId = api_get_current_access_url_id();
if (-1 != $accessUrlId) {
$sql = "SELECT s.id, name FROM $tblSession s
INNER JOIN $tblSessionRelAccessUrl as session_rel_url
ON (s.id = session_rel_url.session_id)
$innerJoinSessionRelUser
WHERE access_url_id = $accessUrlId
$whereCondictionMultiUrl
ORDER BY name";
}
}
$result = Database::query($sql);
$Sessions = Database::store_result($result);
$options = [];
$options['0'] = '';
foreach ($Sessions as $enreg) {
$options[$enreg['id']] = $enreg['name'];
}
$form = new FormValidator('search_user', 'post', api_get_self());
$form->addElement('select', 'session_id', get_lang('SessionList'), $options, ['id' => 'session-id']);
$form->addDatePicker('date_begin', get_lang('DateStart'), ['id' => 'date-begin']);
$form->addDatePicker('date_end', get_lang('DateEnd'), ['id' => 'date-end']);
// EXTRA FIELDS
$extraField = new ExtraField('user');
$returnParams = $extraField->addElements(
$form,
0,
[],
true,
false,
[],
[],
[],
false,
true
);
$form->addElement('hidden', 'formSent', 1);
$form->addButtonSearch(get_lang('Search'));
$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('MySpace')];
Display::display_header(get_lang('CertificatesSessions'));
@ -299,7 +353,7 @@ echo $form->returnForm();
if (0 == count($certificateList)) {
echo Display::return_message(get_lang('NoResultsAvailable'), 'warning');
} else {
echo '<table class="table data_table">';
echo '<table class="table table-hover table-striped data_table">';
echo '<tbody>';
foreach ($certificateList as $index => $value) {
$categoryId = $value['category_id'];
@ -313,7 +367,7 @@ if (0 == count($certificateList)) {
echo '<td width="50%" class="actions">'.$courseInfo['title'].'</td>';
echo '</tr>';
echo '<tr><td colspan="2">
<table class="table data_table">
<table class="table table-hover table-striped data_table">
<tbody>';
$list = GradebookUtils::get_list_gradebook_certificates_by_user_id($value['user_id'], $categoryId);

@ -21,28 +21,28 @@ if (!$allowToTrack) {
$nameTools = get_lang('Learners');
$export_csv = isset($_GET['export']) && 'csv' == $_GET['export'] ? true : false;
$export_csv = isset($_GET['export']) && 'csv' === $_GET['export'] ? true : false;
$keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
$active = isset($_GET['active']) ? intval($_GET['active']) : 1;
$sleepingDays = isset($_GET['sleeping_days']) ? intval($_GET['sleeping_days']) : null;
$active = isset($_GET['active']) ? (int) $_GET['active'] : 1;
$sleepingDays = isset($_GET['sleeping_days']) ? (int) $_GET['sleeping_days'] : null;
$this_section = SECTION_TRACKING;
$webCodePath = api_get_path(WEB_CODE_PATH);
$interbreadcrumb[] = [
"url" => api_is_student_boss() ? "#" : "index.php",
"name" => get_lang('Reporting'),
'url' => api_is_student_boss() ? '#' : 'index.php',
'name' => get_lang('Reporting'),
];
if (isset($_GET["user_id"]) && "" != $_GET["user_id"] && !isset($_GET["type"])) {
if (isset($_GET['user_id']) && '' != $_GET['user_id'] && !isset($_GET['type'])) {
$interbreadcrumb[] = [
"url" => "teachers.php",
"name" => get_lang('Teachers'),
'url' => 'teachers.php',
'name' => get_lang('Teachers'),
];
}
if (isset($_GET["user_id"]) && "" != $_GET["user_id"] && isset($_GET["type"]) && "coach" == $_GET["type"]) {
$interbreadcrumb[] = ["url" => "coaches.php", "name" => get_lang('Coaches')];
if (isset($_GET['user_id']) && '' != $_GET['user_id'] && isset($_GET['type']) && 'coach' === $_GET['type']) {
$interbreadcrumb[] = ['url' => 'coaches.php', 'name' => get_lang('Coaches')];
}
function get_count_users()

@ -113,7 +113,6 @@ function get_users($from, $limit, $column, $direction)
$all_datas = [];
$url = api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php';
foreach ($students as $student_data) {
var_dump($student_data);
$student_id = $student_data['user_id'];
$student_data = api_get_user_info($student_id);
if (isset($_GET['id_session'])) {

@ -143,6 +143,8 @@ $form->addLabel(
$form->addButtonUpdate(get_lang('Edit'), 'submit_survey');
$surveyData['start_date'] = api_get_local_time($surveyData['start_date']);
$surveyData['end_date'] = api_get_local_time($surveyData['end_date']);
$form->setDefaults($surveyData);
// The validation or display

@ -4,6 +4,7 @@
use ChamiloSession as Session;
$lastQuestion = 0;
/**
* @author unknown, the initial survey that did not make it in 1.8 because of bad code
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup,
@ -572,7 +573,7 @@ if (
Session::erase('page_questions_sec');
$paged_questions_sec = [];
if (!empty($survey_data['survey_introduction'])) {
echo '<div class="survey_content">'.$survey_data['survey_introduction'].'</div>';
echo '<div class="survey_content">'.Security::remove_XSS($survey_data['survey_introduction']).'</div>';
}
$limit = 0;
}
@ -639,7 +640,7 @@ if ($survey_data['form_fields'] &&
// Displaying the survey thanks message
if (isset($_POST['finish_survey'])) {
echo Display::return_message(get_lang('You have finished this survey.'), 'confirm');
echo $survey_data['survey_thanks'];
echo Security::remove_XSS($survey_data['survey_thanks']);
SurveyManager::update_survey_answered(
$survey_data,
@ -653,6 +654,7 @@ if (isset($_POST['finish_survey'])) {
);
if ($courseInfo && !api_is_anonymous()) {
echo '<br /><br />';
echo Display::toolbarButton(
get_lang('Return to Course Homepage'),
api_get_course_url($courseInfo['code']),
@ -807,6 +809,11 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
$questions[$sort]['parent_option_id'] = isset($row['parent_option_id']) ? $row['parent_option_id'] : 0;
}
$counter++;
if (isset($_GET['show']) && (int) $_GET['show'] >= 0) {
$lastQuestion = (int) $_GET['show'] - 1;
} else {
$lastQuestion = (int) $row['question_option_id'];
}
}
}
} elseif ('1' === $survey_data['survey_type']) {
@ -1340,6 +1347,17 @@ if ('0' == $survey_data['survey_type']) {
'success'
);
} else {
if (
api_get_configuration_value('survey_backwards_enable')
) {
if ($lastQuestion >= 0) {
$form->addHtml(
"<a class=\" btn btn-warning \" href=\"$url&show=$lastQuestion\">".
"<em class=\"fa fa-arrow-left\"></em> "
.get_lang('Back')." </a>"
);
}
}
$form->addButton(
'next_survey_page',
get_lang('Next'),

@ -26,10 +26,7 @@ if (0 == $survey_data['anonymous']) {
} else {
$people_filled_full_data = false;
}
$people_filled = SurveyManager::get_people_who_filled_survey(
$survey_id,
$people_filled_full_data
);
$people_filled = SurveyManager::get_people_who_filled_survey($survey_id, $people_filled_full_data);
// Checking the parameters
SurveyUtil::check_parameters($people_filled);
@ -40,7 +37,7 @@ $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
);
/** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
if (!api_is_allowed_to_edit(false, true) || $isDrhOfCourse) {
if ($isDrhOfCourse || !api_is_allowed_to_edit(false, true)) {
// Show error message if the survey can be seen only by tutors
if (SURVEY_VISIBLE_TUTOR == $survey_data['visible_results']) {
api_not_allowed(true);
@ -135,6 +132,85 @@ if ('overview' == $action) {
}
}
$htmlHeadXtra[] = '<script>
async function exportToPdf() {
window.jsPDF = window.jspdf.jsPDF;
$(".question-item img, #pdf_table img").hide();
$(".question-item video, #pdf_table video").hide();
$(".question-item audio, #pdf_table audio").hide();
var doc = document.getElementById("question_results");
var pdf = new jsPDF("", "pt", "a4");
//var a4Height = 841.89;
// Adding title
pdf.setFontSize(16);
pdf.text(40, 40, "'.get_lang('Reporting').'");
const table = document.getElementById("pdf_table");
var headerY = 0;
await html2canvas(table).then(function(canvas) {
var pageData = canvas.toDataURL("image/jpeg", 1);
headerY = 530.28/canvas.width * canvas.height;
pdf.addImage(pageData, "JPEG", 40, 60, 530, headerY);
});
var divs = doc.getElementsByClassName("question-item");
var pages = [];
var page = 1;
for (var i = 0; i < divs.length; i += 1) {
// Two parameters after addImage control the size of the added image,
// where the page height is compressed according to the width-height ratio column of a4 paper.
if (!pages[page]) {
pages[page] = 0;
}
var positionY = 180;
pages[page] += 1;
var diff = 250;
if (page > 1) {
headerY = 0;
positionY = 60;
diff = 220;
}
if (pages[page] > 1) {
positionY = pages[page] * diff + 10;
}
const title = $(divs[i]).find(".title-question");
pdf.setFontSize(12);
pdf.text(40, positionY, title.text());
var svg = divs[i].querySelector("svg");
svg2pdf(svg, pdf, {
xOffset: 10,
yOffset: positionY + 10,
scale: 0.45
});
var tables = divs[i].getElementsByClassName("display-survey");
var config= {};
for (var j = 0; j < tables.length; j += 1) {
await html2canvas(tables[j], config).then(function(canvas) {
var pageData = canvas.toDataURL("image/jpeg", 0.8);
pdf.addImage(pageData, "JPEG", 40, positionY + 200, 500, 500/canvas.width * canvas.height);
});
}
if (i > 0 && (i -1) % 2 === 0 && (i+1 != divs.length)) {
pdf.addPage();
page++;
}
}
$(".question-item img, #pdf_table img").show();
$(".question-item video, #pdf_table video").show();
$(".question-item audio, #pdf_table audio").show();
pdf.save("reporting.pdf");
}
</script>';
// Displaying the header
Display::display_header($tool_name, 'Survey');

@ -69,6 +69,8 @@ function check_download_survey($course, $invitation, $doc_url)
$survey_invitation['survey_id'] = $row['survey_id'];
}
$doc_url = Database::escape_string($doc_url);
$survey_invitation['survey_id'] = Database::escape_string($survey_invitation['survey_id']);
$sql = "SELECT count(*)
FROM $table_survey
WHERE
@ -85,8 +87,8 @@ function check_download_survey($course, $invitation, $doc_url)
WHERE
c_id = $course_id AND
survey_id = ".$survey_invitation['survey_id']." AND (
survey_question LIKE '%$doc_url%'
or survey_question_comment LIKE '%$doc_url%'
survey_question LIKE '%$doc_url%' OR
survey_question_comment LIKE '%$doc_url%'
)
UNION
SELECT count(*)

@ -372,9 +372,15 @@ class SurveyManager
$survey_id = $survey->getIid();
if ($survey_id > 0) {
$sql = "UPDATE $table_survey SET survey_id = $survey_id
WHERE iid = $survey_id";
Database::query($sql);
Event::addEvent(
LOG_SURVEY_CREATED,
LOG_SURVEY_ID,
$survey_id,
null,
api_get_user_id(),
api_get_course_int_id(),
api_get_session_id()
);
// Insert into item_property
api_item_property_update(
@ -659,6 +665,15 @@ class SurveyManager
Database::query($sql);
}
Event::addEvent(
LOG_SURVEY_DELETED,
LOG_SURVEY_ID,
$survey_id,
null,
api_get_user_id(),
api_get_course_int_id(),
api_get_session_id()
);
// Deleting groups of this survey
$sql = "DELETE FROM $table_survey_question_group
WHERE c_id = $course_id AND survey_id='".$survey_id."'";
@ -864,6 +879,15 @@ class SurveyManager
WHERE c_id = '.$courseId.' AND survey_id='.$surveyId;
Database::query($sql);
Event::addEvent(
LOG_SURVEY_CLEAN_RESULTS,
LOG_SURVEY_ID,
$surveyId,
null,
api_get_user_id(),
api_get_course_int_id(),
api_get_session_id()
);
return true;
}
@ -2379,6 +2403,14 @@ class SurveyManager
return false;
}
$extraFieldValue = new ExtraFieldValue('survey');
$groupData = $extraFieldValue->get_values_by_handler_and_field_variable($surveyId, 'group_id');
$groupId = null;
if ($groupData && !empty($groupData['value'])) {
$groupId = (int) $groupData['value'];
}
if (null === $groupId) {
$obj = new UserGroup();
$options['where'] = [' usergroup.course_id = ? ' => $courseId];
$classList = $obj->getUserGroupInCourse($options);
@ -2395,23 +2427,25 @@ class SurveyManager
];
}
self::parseMultiplicateUserList($classToParse, $questions, $courseId, $surveyData);
$extraFieldValue = new ExtraFieldValue('survey');
$groupData = $extraFieldValue->get_values_by_handler_and_field_variable($surveyId, 'group_id');
if ($groupData && !empty($groupData['value'])) {
$groupInfo = GroupManager::get_group_properties($groupData['value']);
self::parseMultiplicateUserList($classToParse, $questions, $courseId, $surveyData, true);
} else {
$groupInfo = GroupManager::get_group_properties($groupId);
if (!empty($groupInfo)) {
$users = GroupManager::getStudents($groupInfo['iid'], true);
if (!empty($users)) {
$users = array_column($users, 'id');
$classToParse = [
self::parseMultiplicateUserList(
[
[
'name' => $groupInfo['name'],
'users' => $users,
],
];
self::parseMultiplicateUserList($classToParse, $questions, $courseId, $surveyData);
],
$questions,
$courseId,
$surveyData,
false
);
}
}
}
@ -2419,7 +2453,7 @@ class SurveyManager
return true;
}
public static function parseMultiplicateUserList($itemList, $questions, $courseId, $surveyData)
public static function parseMultiplicateUserList($itemList, $questions, $courseId, $surveyData, $addClassNewPage = false)
{
if (empty($itemList) || empty($questions)) {
return false;
@ -2490,7 +2524,7 @@ class SurveyManager
}
}
if ($classCounter < count($itemList)) {
if ($addClassNewPage && $classCounter < count($itemList)) {
// Add end page
$values = [
'c_id' => $courseId,

@ -221,9 +221,9 @@ class SurveyUtil
Display::display_header($tool_name);
Display::display_footer();
exit;
} else {
return true;
}
return true;
}
/**
@ -575,7 +575,7 @@ class SurveyUtil
$offset = !isset($_GET['question']) ? 0 : (int) $_GET['question'];
$currentQuestion = isset($_GET['question']) ? (int) $_GET['question'] : 0;
$surveyId = (int) $survey_data['survey_id'];
$action = Security::remove_XSS($_GET['action']);
$action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
$course_id = api_get_course_int_id();
// Database table definitions
@ -585,14 +585,40 @@ class SurveyUtil
$questions = [];
echo '<div class="actions">';
echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'.
echo '<a
href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'.
Display::return_icon(
'back.png',
get_lang('Back to').' '.get_lang('Reporting overview'),
'',
ICON_SIZE_MEDIUM
).'</a>';
echo Display::url(
Display::return_icon(
'pdf.png',
get_lang('ExportToPdf'),
'',
ICON_SIZE_MEDIUM
),
'javascript: void(0);',
['onclick' => 'exportToPdf();']
);
echo '</div>';
$fromUntil = sprintf(get_lang('FromXUntilY'), $survey_data['avail_from'], $survey_data['avail_till']);
$data = [
get_lang('SurveyTitle') => $survey_data['title'],
get_lang('SurveySubTitle') => $survey_data['subtitle'],
get_lang('Dates') => $fromUntil,
get_lang('SurveyIntroduction') => $survey_data['intro'],
];
$table = new HTML_Table(['id' => 'pdf_table', 'class' => 'table']);
$row = 0;
foreach ($data as $label => $item) {
$table->setCellContents($row, 0, $label);
$table->setCellContents($row, 1, $item);
$row++;
}
if ($survey_data['number_of_questions'] > 0) {
$limitStatement = null;
@ -636,7 +662,9 @@ class SurveyUtil
$questions[$row['question_id']] = $row;
}
}
echo '<div id="question_results">';
foreach ($questions as $question) {
echo '<div class="question-item">';
$chartData = [];
$options = [];
$questionId = (int) $question['question_id'];
@ -705,18 +733,19 @@ class SurveyUtil
array_push($chartData, ['option' => $optionText, 'votes' => $votes]);
}
$chartContainerId = 'chartContainer'.$question['question_id'];
echo '<div id="'.$chartContainerId.'" class="col-md-12">';
echo '<div id="'.$chartContainerId.'" >';
echo self::drawChart($chartData, false, $chartContainerId, false);
echo '</div>';
echo self::drawChart($chartData, false, $chartContainerId);
// displaying the table: headers
echo '<table class="display-survey table">';
echo '<table class="display-survey table" id="table_'.$chartContainerId.'">';
echo ' <tr>';
echo ' <th>&nbsp;</th>';
echo ' <th>'.get_lang('Absolute total').'</th>';
echo ' <th>'.get_lang('Percentage').'</th>';
echo ' <th>'.get_lang('Graphic').'</th>';
echo ' <tr>';
echo ' </tr>';
// Displaying the table: the content
if (is_array($options)) {
@ -756,8 +785,11 @@ class SurveyUtil
echo ' <td class="center">';
$size = $answers_number * 2;
if ($size > 0) {
echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'
.$size.'px">&nbsp;</div>';
echo '<div
style="border:1px solid #264269; background-color:#aecaf4; height:10px;
width:'.$size.'px">
&nbsp;
</div>';
} else {
echo '<div style="text-align: left;">'.get_lang("No data available").'</div>';
}
@ -776,16 +808,21 @@ class SurveyUtil
}
// displaying the table: footer (totals)
echo ' <tr>';
echo ' <td class="total"><b>'.get_lang('Total').'</b></td>';
echo ' <td class="total"><b>'.$optionResult.'</b></td>';
echo ' <td class="total">&nbsp;</td>';
echo ' <td class="total">&nbsp;</td>';
echo ' </tr>';
echo '</table>';
echo ' <tr>
<td class="total"><b>'.get_lang('Total').'</b></td>
<td class="total"><b>'.$optionResult.'</b></td>
<td class="total">&nbsp;</td>
<td class="total">&nbsp;</td>
</tr>
</table>';
}
echo '</div>';
}
}
echo '</div>';
// Survey information, needed for the PDF export.
echo Display::page_subheader(get_lang('Survey')).'<br />';
$table->display();
if (isset($_GET['viewoption'])) {
echo '<div class="answered-people">';
@ -892,7 +929,7 @@ class SurveyUtil
echo ' <th>'.get_lang('Absolute total').'</th>';
echo ' <th>'.get_lang('Percentage').'</th>';
echo ' <th>'.get_lang('Graphic').'</th>';
echo ' <tr>';
echo ' </tr>';
// Displaying the table: the content
foreach ($options as $key => &$value) {
for ($i = 1; $i <= $question['max_value']; $i++) {
@ -1004,7 +1041,7 @@ class SurveyUtil
.$surveyId.'&'.api_get_cidreq().'">';
// The table
$content .= '<br /><table class="data_table" border="1">';
$content .= '<br /><table class="table table-hover table-striped data_table" border="1">';
// Getting the number of options per question
$content .= ' <tr>';
$content .= ' <th>';
@ -2917,6 +2954,7 @@ class SurveyUtil
$table->set_column_filter(8, 'anonymous_filter');
$actions = [
'export_all' => get_lang('ExportResults'),
'export_by_class' => get_lang('ExportByClass'),
'send_to_tutors' => get_lang('SendToGroupTutors'),
'multiplicate' => get_lang('MultiplicateQuestions'),
'delete' => get_lang('DeleteSurvey'),
@ -3836,62 +3874,69 @@ class SurveyUtil
*
* @return string (direct output)
*/
public static function drawChart(
$chartData,
$hasSerie = false,
$chartContainerId = 'chartContainer'
) {
public static function drawChart($chartData, $hasSerie = false, $chartContainerId = 'chartContainer', $loadLibs = true)
{
$htmlChart = '';
if (api_browser_support('svg')) {
$htmlChart .= api_get_js('d3/d3.v3.5.4.min.js');
$htmlChart .= api_get_js('dimple.v2.1.2.min.js').'
<script>
var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
var data = [';
$serie = [];
$order = [];
$data = '';
foreach ($chartData as $chartDataElement) {
$htmlChart .= '{"';
$data .= '{"';
$option = str_replace(["\n", "\r"], '', $chartDataElement['option']);
$serieValue = isset($chartDataElement['serie']) ? $chartDataElement['serie'] : null;
if (!$hasSerie) {
$htmlChart .= get_lang("Option").'":"'.$chartDataElement['option'].'", "';
array_push($order, $chartDataElement['option']);
$data .= get_lang("Option").'":"'.$option.'", "';
array_push($order, $option);
} else {
if (!is_array($chartDataElement['serie'])) {
$htmlChart .= get_lang("Option").'":"'.$chartDataElement['serie'].'", "'.
get_lang("Score").'":"'.$chartDataElement['option'].'", "';
array_push($serie, $chartDataElement['serie']);
if (!is_array($serieValue)) {
$data .=
get_lang("Option").'":"'.$serieValue.'", "'.
get_lang("Score").'":"'.$option.'", "';
array_push($serie, $serieValue);
} else {
$htmlChart .= get_lang("Serie").'":"'.$chartDataElement['serie'][0].'", "'.
get_lang("Option").'":"'.$chartDataElement['serie'][1].'", "'.
get_lang("Score").'":"'.$chartDataElement['option'].'", "';
$data .=
get_lang("Serie").'":"'.$serieValue[0].'", "'.
get_lang("Option").'":"'.$serieValue[1].'", "'.
get_lang("Score").'":"'.$option.'", "';
}
}
$htmlChart .= get_lang("Votes").'":"'.$chartDataElement['votes'].
'"},';
$data .= get_lang("Votes").'":"'.$chartDataElement['votes'].'"},';
rtrim($data, ",");
}
rtrim($htmlChart, ",");
$htmlChart .= '];
if ($loadLibs) {
$htmlChart .= api_get_js('d3/d3.v3.5.4.min.js');
$htmlChart .= api_get_js('dimple.v2.1.2.min.js');
}
$htmlChart .= '
<script>
var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
var data = ['.$data.'];
var myChart = new dimple.chart(svg, data);
myChart.addMeasureAxis("y", "'.get_lang("Votes").'");';
if (!$hasSerie) {
$htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", "'.get_lang("Option").'");
$htmlChart .= '
var xAxisCategory = myChart.addCategoryAxis("x", "'.get_lang("Option").'");
xAxisCategory.addOrderRule('.json_encode($order).');
myChart.addSeries("'.get_lang("Option").'", dimple.plot.bar);';
} else {
if (!is_array($chartDataElement['serie'])) {
$serie = array_values(array_unique($serie));
$htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", ["'.get_lang("Option").'","'
.get_lang("Score").'"]);
$htmlChart .= '
var xAxisCategory =
myChart.addCategoryAxis("x", ["'.get_lang("Option").'","'.get_lang("Score").'"]);
xAxisCategory.addOrderRule('.json_encode($serie).');
xAxisCategory.addGroupOrderRule("'.get_lang("Score").'");
myChart.addSeries("'.get_lang("Option").'", dimple.plot.bar);';
} else {
$htmlChart .= 'myChart.addCategoryAxis("x", ["'.get_lang("Option").'","'.get_lang("Score").'"]);
$htmlChart .= '
myChart.addCategoryAxis("x", ["'.get_lang("Option").'","'.get_lang("Score").'"]);
myChart.addSeries("'.get_lang("Serie").'", dimple.plot.bar);';
}
}
$htmlChart .= 'myChart.draw();
</script>';
$htmlChart .= 'myChart.draw();';
$htmlChart .= '</script>';
}
return $htmlChart;

@ -104,7 +104,7 @@ echo '</a></li>';
echo '</ul>';
// Table header
echo '<table class="data_table" style="margin-top: 5px;">';
echo '<table class="table table-hover table-striped data_table" style="margin-top: 5px;">';
echo ' <tr>';
echo ' <th>'.get_lang('User').'</th>';
echo ' <th>'.get_lang('Invitation date').'</th>';

@ -86,6 +86,288 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
api_not_allowed(true);
}
switch ($action) {
case 'export_by_class':
$surveyList = [];
$course_id = api_get_course_int_id();
$extraFieldValue = new ExtraFieldValue('survey');
$table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
$table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
$table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
foreach ($_POST['id'] as $value) {
$surveyData = SurveyManager::get_survey($value);
$surveyId = $surveyData['survey_id'];
if (empty($surveyData)) {
continue;
}
$surveyData['title'] = api_html_entity_decode(trim(strip_tags($surveyData['title'])));
$groupData = $extraFieldValue->get_values_by_handler_and_field_variable(
$surveyId,
'group_id'
);
$groupTitle = '';
if ($groupData && !empty($groupData['value'])) {
$groupInfo = GroupManager::get_group_properties($groupData['value']);
if ($groupInfo['name']) {
$groupTitle = api_html_entity_decode($groupInfo['name']);
}
}
$surveyData['group_title'] = $groupTitle;
$firstUser = '';
$table = Database::get_course_table(TABLE_SURVEY_INVITATION);
$sql = "SELECT * FROM $table
WHERE
answered = 1 AND
c_id = $course_id AND
session_id = $sessionId AND
survey_code = '".Database::escape_string($surveyData['code'])."'
";
$result = Database::query($sql);
$usersWithAnswers = [];
while ($row = Database::fetch_array($result)) {
if (isset($usersWithAnswers[$row['user']])) {
continue;
}
$userInfo = api_get_user_info($row['user']);
$usersWithAnswers[$row['user']] = $userInfo;
}
$sql = "SELECT
survey_question.question_id,
survey_question.survey_id,
survey_question.survey_question,
survey_question.display,
survey_question.max_value,
survey_question.sort,
survey_question.type,
survey_question_option.question_option_id,
survey_question_option.option_text,
survey_question_option.sort as option_sort
FROM $table_survey_question survey_question
LEFT JOIN $table_survey_question_option survey_question_option
ON
survey_question.question_id = survey_question_option.question_id AND
survey_question_option.c_id = $course_id
WHERE
survey_question NOT LIKE '%{{%' AND
survey_question.survey_id = '".$surveyId."' AND
survey_question.c_id = $course_id
ORDER BY survey_question.sort, survey_question_option.sort ASC";
$result = Database::query($sql);
$questionsOptions = [];
while ($row = Database::fetch_array($result, 'ASSOC')) {
if ($row['type'] != 'pagebreak') {
$questionsOptions[$row['sort']]['question_id'] = $row['question_id'];
$questionsOptions[$row['sort']]['survey_id'] = $row['survey_id'];
$questionsOptions[$row['sort']]['survey_question'] = $row['survey_question'];
$questionsOptions[$row['sort']]['display'] = $row['display'];
$questionsOptions[$row['sort']]['type'] = $row['type'];
$questionsOptions[$row['sort']]['maximum_score'] = $row['max_value'];
$questionsOptions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
}
}
$sql = "SELECT * FROM $table_survey_answer
WHERE c_id = $course_id AND survey_id = $surveyId ";
$userAnswers = [];
$all_answers = [];
$result = Database::query($sql);
while ($answers_of_user = Database::fetch_array($result, 'ASSOC')) {
$userAnswers[$answers_of_user['user']][$surveyId][$answers_of_user['question_id']][] = $answers_of_user['option_id'];
$all_answers[$answers_of_user['user']][$answers_of_user['question_id']][] = $answers_of_user;
}
foreach ($questionsOptions as $question) {
foreach ($usersWithAnswers as $userData) {
$userIdItem = $userData['user_id'];
// If the question type is a scoring then we have to format the answers differently
switch ($question['type']) {
/*case 'score':
$finalAnswer = [];
if (is_array($question) && is_array($all_answers)) {
foreach ($all_answers[$question['question_id']] as $key => &$answer_array) {
$finalAnswer[$answer_array['option_id']] = $answer_array['value'];
}
}
break;*/
case 'multipleresponse':
$finalAnswer = isset($userAnswers[$userIdItem][$surveyId][$question['question_id']]) ? $userAnswers[$userIdItem][$surveyId][$question['question_id']] : '';
if (is_array($finalAnswer)) {
$items = [];
foreach ($finalAnswer as $option) {
foreach ($question['options'] as $optionId => $text) {
if ($option == $optionId) {
$items[] = api_html_entity_decode(strip_tags($text));
}
}
}
$finalAnswer = implode(' - ', $items);
}
break;
default:
$finalAnswer = '';
if (isset($all_answers[$userIdItem][$question['question_id']])) {
$finalAnswer = $all_answers[$userIdItem][$question['question_id']][0]['option_id'];
foreach ($question['options'] as $optionId => $text) {
if ($finalAnswer == $optionId) {
$finalAnswer = api_html_entity_decode(strip_tags($text));
break;
}
}
}
break;
}
$userAnswers[$userIdItem][$surveyId][$question['question_id']] = $finalAnswer;
}
}
$surveyData['user_with_answers'] = $usersWithAnswers;
$surveyData['user_answers'] = $userAnswers;
$surveyData['questions'] = SurveyManager::get_questions($surveyId);
$surveyList[] = $surveyData;
}
$userGroup = new UserGroup();
$options = [];
$options['where'] = [' usergroup.course_id = ? ' => $course_id];
$classes = $userGroup->getUserGroupInCourse($options, 0);
@$spreadsheet = new PHPExcel();
$counter = 0;
foreach ($classes as $class) {
$users = $userGroup->getUserListByUserGroup($class['id'], 'u.lastname ASC');
$page = @$spreadsheet->createSheet($counter);
@$page->setTitle($class['name']);
$firstColumn = 3;
$column = 3;
$columnQuestion = 3;
foreach ($surveyList as $survey) {
$questions = $survey['questions'];
$usersWithAnswers = $survey['user_with_answers'];
foreach ($usersWithAnswers as $userAnswer) {
$userId = $userAnswer['user_id'];
$cell = @$page->setCellValueByColumnAndRow(
$column,
1,
//$survey['title'].$survey['group_title'].' - '.$userAnswer['complete_name']
$survey['group_title'].' - '.$userAnswer['complete_name']
);
$coordinate = $page->getCellByColumnAndRow($column, 1)->getCoordinate();
/*if (!empty($coordinate)) {
$dimension = $cell->getColumnDimension($coordinate);
if ($dimension) {
$cell->getColumnDimension($coordinate)->setAutoSize(false);
$cell->getColumnDimension($coordinate)->setWidth("120");
}
}*/
//$page->getCellByColumnAndRow($column, 1)->getColumnDimension($coordinate)->setWidth(80);
$questionCounter = 0;
$firstCoordinate = $coordinate;
$lastCoordinate = '';
foreach ($questions as $question) {
$questionTitle = $question['question'];
if (strpos($question['question'], '{{')) {
$questionPosition = $column + $questionCounter;
$cell = @$page->setCellValueByColumnAndRow(
$questionPosition,
2,
strip_tags($questionTitle),
true
);
//$coordinate = @$page->getCellByColumnAndRow($questionPosition, 2)->getCoordinate();
//$page->getColumnDimension($coordinate);
/*$dimension = @$page->getColumnDimension($questionPosition);
if ($dimension) {
$dimension->setAutoSize(true);
$dimension->setWidth(200);
//$cell->getColumnDimension($coordinate)->setAutoSize(false);
//$cell->getColumnDimension($coordinate)->setWidth("120");
}*/
$coordinate = $page->getCellByColumnAndRow($questionPosition, 1)->getCoordinate();
$lastCoordinate = $coordinate;
$rowStudent = 3;
foreach ($users as $user) {
$completeName = $user['firstname'].' '.$user['lastname'];
$questionTitle = str_replace(
'{{student_full_name}}',
$completeName,
$question['question']
);
foreach ($questions as $questionData) {
if (strpos($questionData['question'], '{{') === false) {
if ($questionTitle === $questionData['question']) {
foreach ($survey['user_answers'][$userId][$survey['survey_id']] as $questionId => $answerData) {
if ($questionData['question_id'] == $questionId) {
if (is_array($answerData)) {
$answerData = implode(', ', $answerData);
}
@$page->setCellValueByColumnAndRow(
$questionPosition,
$rowStudent,
$answerData,
true
);
break;
}
}
break;
}
}
}
$rowStudent++;
}
$questionCounter++;
$columnQuestion++;
}
}
$column += $questionCounter;
$columnQuestion = $column;
if (!empty($lastCoordinate)) {
$page->mergeCells($firstCoordinate.':'.$lastCoordinate);
}
}
$questionPerUser = [];
foreach ($questions as $question) {
if (strpos($question['question'], '{{')) {
} else {
foreach ($users as $user) {
$completeName = $user['firstname'].' '.$user['lastname'];
if (strpos($question['question'], $completeName)) {
break;
}
$questionPerUser[$user['id']][] = $question['question_id'];
}
}
}
}
$row = 2;
foreach ($users as $user) {
$userId = $user['id'];
$columnUser = 0;
@$page->setCellValueByColumnAndRow($columnUser++, $row, $user['lastname']);
@$page->setCellValueByColumnAndRow($columnUser++, $row, $user['firstname']);
$row++;
}
$counter++;
}
$spreadsheet->setActiveSheetIndex(0);
$file = api_get_path(SYS_ARCHIVE_PATH).uniqid('report', true);
@$writer = new PHPExcel_Writer_Excel2007($spreadsheet);
@$writer->save($file);
DocumentManager::file_send_for_download($file, true, get_lang('Report').'.xlsx');
break;
}
$exportList = [];
foreach ($_POST['id'] as $value) {
$surveyData = SurveyManager::get_survey($value);

@ -25,7 +25,7 @@ class survey_question
$questions = SurveyManager::get_questions($surveyId);
$newQuestionList = [];
$allowTypes = ['yesno', 'multiplechoice'];
$allowTypes = ['yesno', 'multiplechoice', 'multipleresponse'];
foreach ($questions as $question) {
if (in_array($question['type'], $allowTypes)) {
$newQuestionList[$question['sort']] = $question;
@ -64,7 +64,7 @@ class survey_question
$.getJSON({
url: "'.$url.'" + "&question_id=" + questionId,
success: function(data) {
$("#parent_options").html(data);
$("#option_list").show();
$.each(data, function(key, value) {
$("<option>").val(key).text(value).appendTo($select);
});

Loading…
Cancel
Save